-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathStopwatch.cpp
56 lines (46 loc) · 1.51 KB
/
Stopwatch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <chrono>
class Stopwatch {
private:
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
std::chrono::time_point<std::chrono::high_resolution_clock> endTime;
bool running;
public:
Stopwatch() : running(false) {}
void start() {
if (!running) {
startTime = std::chrono::high_resolution_clock::now();
running = true;
} else {
std::cout << "Stopwatch is already running. Use stop() before starting again." << std::endl;
}
}
void stop() {
if (running) {
endTime = std::chrono::high_resolution_clock::now();
running = false;
} else {
std::cout << "Stopwatch is not running. Use start() before stopping." << std::endl;
}
}
double getElapsedTimeInSeconds() {
if (running) {
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(now - startTime).count();
} else {
return std::chrono::duration<double>(endTime - startTime).count();
}
}
double getElapsedTimeInMilliseconds() {
return getElapsedTimeInSeconds() * 1000.0;
}
};
int main() {
Stopwatch stopwatch;
stopwatch.start();
// Simulate some work with a sleep
std::this_thread::sleep_for(std::chrono::seconds(2));
stopwatch.stop();
std::cout << "Elapsed time: " << stopwatch.getElapsedTimeInMilliseconds() << " ms" << std::endl;
return 0;
}