Skip to content

Instantly share code, notes, and snippets.

@justgord
Created January 8, 2013 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justgord/4482447 to your computer and use it in GitHub Desktop.
Save justgord/4482447 to your computer and use it in GitHub Desktop.
C++11 scoped timer class and usage
// C++11 scoped timer class and usage
//
// an example of RAII 'resource acquisition is initialisation' idiom
// build : g++ -Wall -std=c++11 -O5 -o scoped_timer scoped_timer.cpp
//
// on linux x64 resolution of timer seems to be microseconds [ on win/VC it may be much worse ]
//
// I like this approach as it doesnt litter your existing code with garbage,
// although there might be some inaccuracy due to stack setup/pulldown of the timer class itself
//
// github.com/justgord
//
#include <functional>
#include <chrono>
#include <iostream>
using namespace std;
struct ScopedNanoTimer
{
chrono::high_resolution_clock::time_point t0;
function<void(int)> cb;
ScopedNanoTimer(function<void(int)> callback)
: t0(chrono::high_resolution_clock::now())
, cb(callback)
{
}
~ScopedNanoTimer(void)
{
auto t1 = chrono::high_resolution_clock::now();
auto nanos = chrono::duration_cast<chrono::nanoseconds>(t1-t0).count();
cb(nanos);
}
};
// usage
int main()
{
const int N=10000000;
struct Results
{
void operator()(int ns)
{
cout << "Ops : " << N << endl;
cout << "Nanos : " << ns << endl;
cout << "ns per op : " << (ns/N) << endl;
}
};
Results results;
ScopedNanoTimer Timer(results);
// do some work you want to time
long double sum=0.0;
for (int i=0;i<N;i++)
{
sum += i*45.678;
}
cout << "Sum : " << sum << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment