cgv
Loading...
Searching...
No Matches
stopwatch.cxx
1#include "stopwatch.h"
2
3#include <iostream>
4#include <ctime>
5#ifdef _WIN32
6#ifndef NOMINMAX
7#define NOMINMAX
8#endif
9#include <windows.h>
10#endif
11
12namespace cgv {
13 namespace utils {
14
15#ifdef _WIN32
16static long long frequency;
17static bool queried_perfcounter = false;
18#else
19constexpr auto S_TO_NS=1000000000LL;
20constexpr auto NS_TO_S=(1.0/double(S_TO_NS));
21#endif
22
23void stopwatch::init()
24{
25#ifdef _WIN32
26 if (!queried_perfcounter) {
27 QueryPerformanceFrequency((LARGE_INTEGER*) &frequency);
28 queried_perfcounter = true;
29 }
30 QueryPerformanceCounter((LARGE_INTEGER*) &start);
31#else
32 timespec ts;
33 clock_gettime(CLOCK_MONOTONIC, &ts);
34 start = ((long long)ts.tv_sec)*S_TO_NS + (long long)ts.tv_nsec;
35#endif
36}
37
38//standard constructor starts time measurement
39stopwatch::stopwatch(bool silent) : silent(silent)
40{
41 resultd = 0;
42 init();
43}
44
45//start counting time
46stopwatch::stopwatch(double *result, bool silent) : silent(silent)
47{
48 this->resultd = result;
49 init();
50}
51
52double stopwatch::get_current_time(long long& end) const
53{
54 double time;
55#ifdef _WIN32
56 QueryPerformanceCounter((LARGE_INTEGER*) &end);
57 time =(end-start)/(double)frequency;
58#else
59 timespec ts;
60 clock_gettime(CLOCK_MONOTONIC, &ts);
61 end = ((long long)ts.tv_sec)*S_TO_NS + (long long)ts.tv_nsec;
62 time = double(end - start)*NS_TO_S;
63#endif
64 return time;
65}
66
68double stopwatch::get_elapsed_time() const
69{
70 long long end;
71 return get_current_time(end);
72}
73
75double stopwatch::restart()
76{
77 long long end;
78 double time = get_current_time(end);
79 start = end;
80 return time;
81}
82
83// add_time adds the time ellapsed thus far
84void stopwatch::add_time()
85{
86 double time = restart();
87
88 if(resultd)
89 *resultd += time;
90 else if(!silent)
91 std::cout << "elapsed time in seconds: " << time << std::endl;
92}
93
94//destructor stops time measurement and puts the result into cout
95stopwatch::~stopwatch()
96{
97 add_time();
98}
99
100 }
101}
102
the cgv namespace
Definition print.h:11