Skip to content

A simple C++ 03/11/etc timer class for ~microsecond-precision cross-platform benchmarking. The implementation is as limited and as simple as possible to create the lowest amount of overhead.

License

Notifications You must be signed in to change notification settings

GerHobbelt/plf_nanotimer

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 

Repository files navigation

plf::nanotimer

A simple C++ 03/11/etc timer class for ~microsecond-precision cross-platform benchmarking. The implementation is as limited and simple as possible to afford the lowest amount of overhead.

Use as follows:

#include "plf_nanotimer.hpp"


plf::nanotimer timer;


timer.start()

// Do something here

double results = timer.get_elapsed_ns();
std::cout << "Timing: " << results << " nanoseconds." << std::endl;


timer.start(); // "start" has the same semantics as "restart".

// Do something else

results = timer.get_elapsed_ms();
std::cout << "Timing: " << results << " milliseconds." << std::endl;


timer.start()

plf::microsecond_delay(15); // Delay program for 15 microseconds

results = timer.get_elapsed_us();
std::cout << "Timing: " << results << " microseconds." << std::endl;

Timer member functions:

void start(): start or restart timer

double get_elapsed_ns(): get elapsed time in nanoseconds

double get_elapsed_us(): get elapsed time in microseconds

double get_elapsed_ms(): get elapsed time in milliseconds

Non-member functions:

void plf::millisecond_delay(double x): delay the program until x milliseconds have passed

void plf::microsecond_delay(double x): delay the program until x microseconds have passed

void plf::nanosecond_delay(double x): delay the program until x nanoseconds have passed

Timer 'pausing':

I determined that a 'pause'-style function would add too much complexity to the class for simple benchmarking, which in turn might interfere with performance analysis, so if you need a 'pause' function do something like this:

plf::nanotimer timer;


timer.start()
// Do something here
double results = timer.get_elapsed_ns();

// Do something else - timer 'paused'

timer.start()

// Do stuff

results += timer.get_elapsed_ns();

std::cout << "Timing: " << results << " nanoseconds." << std::endl;

Why not use the CPU's cycle counter (RDTSC) directly?

See https://stackoverflow.com/questions/13772567/how-to-get-the-cpu-cycle-count-in-x86-64-from-c; note the various issues mentioned in the responses there.

About

A simple C++ 03/11/etc timer class for ~microsecond-precision cross-platform benchmarking. The implementation is as limited and as simple as possible to create the lowest amount of overhead.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C 54.5%
  • C++ 45.5%