nsnake
Classic snake game for the terminal
Loading...
Searching...
No Matches
Timer.cpp
1#include <Misc/Timer.hpp>
2
3#include <iostream> // NULL
4
5// How many microseconds exists in a second
6#define MICRO_IN_SECONDS 1000000
7
8// Local functino that returns current microsecond
9// amount since the Epoch.
10//
11static suseconds_t get_ticks()
12{
13 struct timeval tmp;
14 gettimeofday(&(tmp), NULL);
15
16 return tmp.tv_usec + (tmp.tv_sec * MICRO_IN_SECONDS);
17}
18
19Timer::Timer():
20 startMark(0),
21 stopMark(0),
22 pausedMark(0),
23 running(false),
24 paused(false)
25{}
27{
28 this->startMark = get_ticks();
29 this->stopMark = 0;
30 this->pausedMark = 0;
31 this->running = true;
32 this->paused = false;
33}
35{
36 if (!running || paused) return;
37
38 this->pausedMark = get_ticks() - (this->startMark);
39
40 this->running = false;
41 this->paused = true;
42}
44{
45 if (!paused || running) return;
46
47 this->startMark = (get_ticks()) - (this->pausedMark);
48 this->pausedMark = 0;
49
50 this->running = true;
51 this->paused = false;
52}
54{
55 return this->running;
56}
58{
59 return this->paused;
60}
61suseconds_t Timer::delta_us()
62{
63 if (this->isRunning())
64 return get_ticks() - this->startMark;
65
66 if (this->paused)
67 return this->pausedMark;
68
69 // Something went wrong here
70 if (this->startMark == 0)
71 return 0;
72
73 return (this->pausedMark) - (this->startMark);
74}
75suseconds_t Timer::delta_ms()
76{
77 return this->delta_us() / 1000;
78}
79suseconds_t Timer::delta_s()
80{
81 return this->delta_ms() / 1000;
82}
83
void pause()
Temporarily stops the timer.
Definition Timer.cpp:34
bool isRunning()
Tells if the timer's still running (hasn't called stop())
Definition Timer.cpp:53
void start()
Sets a starting point for the timer.
Definition Timer.cpp:26
suseconds_t delta_us()
Returns the whole timer's difference in milisseconds.
Definition Timer.cpp:61
void unpause()
Restarts the timer if it was paused.
Definition Timer.cpp:43
suseconds_t delta_ms()
Returns the milisseconds part of the timer's difference.
Definition Timer.cpp:75
suseconds_t delta_s()
Returns the seconds part of the timer's difference.
Definition Timer.cpp:79
bool isPaused()
Tells if the timer's paused.
Definition Timer.cpp:57