nsnake
Classic snake game for the terminal
Toggle main menu visibility
Loading...
Searching...
No Matches
src
Misc
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
//
11
static
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
19
Timer::Timer():
20
startMark(0),
21
stopMark(0),
22
pausedMark(0),
23
running(false),
24
paused(false)
25
{}
26
void
Timer::start
()
27
{
28
this->startMark = get_ticks();
29
this->stopMark = 0;
30
this->pausedMark = 0;
31
this->running =
true
;
32
this->paused =
false
;
33
}
34
void
Timer::pause
()
35
{
36
if
(!running || paused)
return
;
37
38
this->pausedMark = get_ticks() - (this->startMark);
39
40
this->running =
false
;
41
this->paused =
true
;
42
}
43
void
Timer::unpause
()
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
}
53
bool
Timer::isRunning
()
54
{
55
return
this->running;
56
}
57
bool
Timer::isPaused
()
58
{
59
return
this->paused;
60
}
61
suseconds_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
}
75
suseconds_t
Timer::delta_ms
()
76
{
77
return
this->
delta_us
() / 1000;
78
}
79
suseconds_t
Timer::delta_s
()
80
{
81
return
this->
delta_ms
() / 1000;
82
}
83
Timer::pause
void pause()
Temporarily stops the timer.
Definition
Timer.cpp:34
Timer::isRunning
bool isRunning()
Tells if the timer's still running (hasn't called stop()).
Definition
Timer.cpp:53
Timer::start
void start()
Sets a starting point for the timer.
Definition
Timer.cpp:26
Timer::delta_us
suseconds_t delta_us()
Returns the whole timer's difference in milisseconds.
Definition
Timer.cpp:61
Timer::unpause
void unpause()
Restarts the timer if it was paused.
Definition
Timer.cpp:43
Timer::delta_ms
suseconds_t delta_ms()
Returns the milisseconds part of the timer's difference.
Definition
Timer.cpp:75
Timer::delta_s
suseconds_t delta_s()
Returns the seconds part of the timer's difference.
Definition
Timer.cpp:79
Timer::isPaused
bool isPaused()
Tells if the timer's paused.
Definition
Timer.cpp:57
Generated on
for nsnake by
1.17.0