imate
C++/CUDA Reference
Loading...
Searching...
No Matches
timer.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: Copyright 2021, Siavash Ameli <sameli@berkeley.edu>
3 * SPDX-License-Identifier: BSD-3-Clause
4 * SPDX-FileType: SOURCE
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the license found in the LICENSE.txt file in the root
8 * directory of this source tree.
9 */
10
11
12// =======
13// Headers
14// =======
15
16#include "./timer.h"
17
18#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && \
19 !defined(__CYGWIN__)
20 #include <windows.h> // LARGE_INTEGER, QueryPerformanceFrequency,
21 // QueryPerformanceCounter
22#elif defined(__unix__) || defined(__unix) || \
23 (defined(__APPLE__) && defined(__MACH__))
24 #include <sys/time.h> // timeval, gettimeofday
25#else
26 #error "Unknown compiler"
27#endif
28
29#include <cmath> // NAN
30#include <stdexcept> // std::runtime_error
31
32
33// ===========
34// Constructor
35// ===========
36
39
41 start_time(0),
42 stop_time(0)
43{
44}
45
46
47// ==========
48// Destructor
49// ==========
50
53
55{
56}
57
58
59// =====
60// start
61// =====
62
65
67{
69}
70
71
72// ====
73// stop
74// ====
75
78
80{
82}
83
84
85// =======
86// elapsed
87// =======
88
91
92double Timer::elapsed() const
93{
94 return this->stop_time - this->start_time;
95}
96
97
98// =============
99// get wall time
100// =============
101
104
106{
107 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && \
108 !defined(__CYGWIN__)
109
110 LARGE_INTEGER time, freq;
111 if (!QueryPerformanceFrequency(&freq))
112 {
113 std::runtime_error("Cannot obtain system's time frequency.");
114 return NAN;
115 }
116
117 if (!QueryPerformanceCounter(&time))
118 {
119 std::runtime_error("Cannot obtain elapsed time.");
120 return NAN;
121 }
122
123 return static_cast<double>(time.QuadPart) / \
124 static_cast<double>(freq.QuadPart);
125
126 #elif defined(__unix__) || defined(__unix) || \
127 (defined(__APPLE__) && defined(__MACH__))
128
129 struct timeval time;
130 if (gettimeofday(&time, NULL))
131 {
132 std::runtime_error("Cannot obtain elapsed time.");
133 return NAN;
134 }
135
136 return static_cast<double>(time.tv_sec) + \
137 static_cast<double>(time.tv_usec) * 1e-6;
138
139 #else
140 #error "Unknown compiler"
141 #endif
142}
~Timer()
Destructor for Timer.
Definition timer.cpp:54
void start()
Starts the timer.
Definition timer.cpp:66
static double get_wall_time()
Returns the wall time since the epoch.
Definition timer.cpp:105
Timer()
constructor for Timer
Definition timer.cpp:40
void stop()
Stops the timer.
Definition timer.cpp:79
double start_time
Definition timer.h:64
double elapsed() const
Returns the elapsed time in seconds.
Definition timer.cpp:92
double stop_time
Definition timer.h:65