A computer engineer poking at your cerebral cortex.

C++ Profiler.h

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/
 */
#ifndef PROFILE_H_
#define PROFILE_H_
 
#include <stdio.h>
#include <time.h>
 
//functions:
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);;
}
 
class Profiler
{
	unsigned long long int value1;
	unsigned long long int value2;
	unsigned long long int value3;
 
	time_t start,end;
	double dif;
 
public:
	void startProfiler();
	void stopProfiler();
	void logInfo();
};
 
 
void Profiler::startProfiler()
{
	time (&start);
	value1 = rdtsc();
}
 
void Profiler::stopProfiler()
{
	value2 = rdtsc();
	time (&end);
	Profiler::logInfo();
}
 
void Profiler::logInfo()
{
	//calc value
	value3 = value2 - value1;
 
	//calc time
	dif = difftime (end,start);
 
 
	//Automatically formats the output nicely.
	//Only works on Linux
	cout.imbue(std::locale(""));
 
	cout << "CPU Calculation: " << value3 << endl;
	printf ("Time took %.2lf seconds.\n", dif);
}
#endif /* PROFILE_H_ */