I needed a way to see how long a block of code was taking to run in seconds and also CPU calculations. I used rdtsc even though it isn’t perfect it does provide decent results. What do I mean by decent? Well running the program 10 times the CPU calculations where fairly similar.
* Profile.h -
* This program will do its best job to profile both time and cpu cycle for c++ software.
* Used to output CPU cycles and the amount of seconds it took for the part of code to run.
* This does not work on Windows! Only OS that support the rdtsc value.
* Copyright 2010 Dan Sheffner.
* You may use this work without restrictions, as long as this notice is included.
* The work is provided "as is" without warranty of any kind, neither express nor implied.
* More information can be found here: http://litl.info/
unsigned long long int rdtsc(void)
unsigned a, d;
__asm__ volatile("rdtsc" : "=a" (a), "=d" (d));
return ((unsigned long long) a) | (((unsigned long long) d) << 32);;
unsigned long long int value1;
unsigned long long int value2;
unsigned long long int value3;
value1 = rdtsc();
value2 = rdtsc();
value3 = value2 - value1;
dif = difftime (end,start);
//Automatically formats the output nicely.
//Only works on Linux
cout << "CPU Calculation: " << value3 << endl;
printf ("Time took %.2lf seconds.\n", dif);
#endif /* PROFILE_H_ */