public
Created

A cpp timer class that provides nanosecond resolution

  • Download Gist
timer.cpp
C++
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
/*
* A class that provides a simple timer
* Works in Windows and Linux, resolution is hardware dependant
*
*
* Copyleft Gordon Bailey 2012 - All wrongs reserved
*
* */
 
#include "timer.h"
 
#ifdef _WIN32
 
#include <cstdlib>
 
#include <iostream>
using std::endl;
using std::cerr;
 
timer::timer() : ready(false) {
bool success = QueryPerformanceFrequency(&counter_freq);
if(!success){
cerr << "Error, QueryPerformanceFrequency failed." << endl;
system("pause");
exit(EXIT_FAILURE);
}
}
 
void timer::start() {
ready = false;
bool success = QueryPerformanceCounter(&start_time);
if(!success){
cerr << "Error, QueryPerformanceCounter failed." << endl;
system("pause");
exit(EXIT_FAILURE);
}
}
 
void timer::end(){
ready = true;
bool success = QueryPerformanceCounter(&end_time);
if(!success){
cerr << "Error, QueryPerformanceCounter failed." << endl;
system("pause");
exit(EXIT_FAILURE);
}
}
 
// there is probably some unnecessary typecasting here, but better safe than sorry
double timer::duration(){
if (ready){
return 1e6 * (((double)(end_time.QuadPart - start_time.QuadPart)) / ((double)counter_freq.QuadPart));
}else{
return 0;
}
}
 
#else
 
timer::timer() : ready(false) {}
 
void timer::start() {
ready = false;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
}
 
void timer::end(){
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
ready = true;
}
 
double timer::duration(){
if (ready){
return 1e6 * (difftime(end_time.tv_sec, start_time.tv_sec) + (1e-9 * (double)(end_time.tv_nsec - start_time.tv_nsec)));
}else{
return 0;
}
}
 
#endif
timer.h
C++
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
#ifndef TIMER_H
#define TIMER_H
 
#ifdef _WIN32
#include <Windows.h>
#else
#include <time.h>
#endif
 
class timer{
 
#ifdef _WIN32
LARGE_INTEGER start_time;
LARGE_INTEGER end_time;
LARGE_INTEGER counter_freq;
#else
struct timespec start_time;
struct timespec end_time;
#endif
 
bool ready;
public:
void start();
void end();
double duration();
timer();
};
 
#endif

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.