Last active
August 29, 2015 14:04
-
-
Save jepio/bddf546fb76fe17e56f3 to your computer and use it in GitHub Desktop.
C/C++ structs for wall-clock timing code execution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __CPU_TIMER_H__ | |
#define __CPU_TIMER_H__ | |
#include <time.h> | |
struct CpuTimer { | |
struct timespec start; | |
struct timespec stop; | |
}; | |
typedef struct CpuTimer CpuTimer; | |
void start(CpuTimer *timer) { clock_gettime(CLOCK_REALTIME, &timer->start); } | |
void stop(CpuTimer *timer) { clock_gettime(CLOCK_REALTIME, &timer->stop); } | |
float elapsed(CpuTimer *timer) | |
{ | |
struct timespec *start = &timer->start; | |
struct timespec *stop = &timer->stop; | |
float elapsed = (stop->tv_sec - start->tv_sec) + | |
1e-9 * (stop->tv_nsec - start->tv_nsec); | |
return elapsed; | |
} | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __CPU_TIMER_H__ | |
#define __CPU_TIMER_H__ | |
#include <ctime> | |
class CpuTimer { | |
public: | |
void start() { clock_gettime(CLOCK_REALTIME, &start_); } | |
void stop() { clock_gettime(CLOCK_REALTIME, &stop_); } | |
float elapsed() | |
{ | |
float elapsed = (stop_.tv_sec - start_.tv_sec) + | |
1e-9 * (stop_.tv_nsec - start_.tv_nsec); | |
return elapsed; | |
} | |
private: | |
timespec start_; | |
timespec stop_; | |
}; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Portable C++11 timer. | |
#pragma once | |
#include <chrono> | |
using namespace std::chrono; | |
class CpuTimer { | |
public: | |
void start() { t1 = high_resolution_clock::now(); } | |
void stop() { t2 = high_resolution_clock::now(); } | |
double elapsed() | |
{ | |
return duration_cast<duration<double>>(t2 - t1).count(); | |
} | |
private: | |
high_resolution_clock::time_point t1, t2; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create an instance of the struct/class, invoke start before a section to be timed, stop after, and then print the elapsed time.
C++:
C: