Execution time :: C & Win

Once in a while I happen to have to know how much time a certain function needs to be executed.
While many programming languages have built in functions (time in Python, System.nanoTime() in Java and so on) to get this information, C doesn’t appear to have one.
There is timec.h but it appears to be quite inaccurate, so if extremely high accuracy is needed we have to rely on something else; the downside is that these much more reliable libraries are not platform independent.
For Windows platform Microsoft suggests to use QueryPerformanceFrequency method and so I did.
Digging through Google I found a post in which a guy posted some C++ code he used to query system time, I’ve adapted it and used it in my program.
For future reference I’m going to post it here.

// global variables
double freq_;
unsigned __int64 baseTime_;

double seconds() {
	unsigned __int64 val;
    QueryPerformanceCounter( (LARGE_INTEGER *)&val );
    return (val - baseTime_) * freq_;

void reset() {
	unsigned __int64 pf;
    QueryPerformanceFrequency( (LARGE_INTEGER *)&pf );
    freq_ = 1.0 / (double)pf;
    QueryPerformanceCounter( (LARGE_INTEGER *)&baseTime_ );

Usage is pretty straight forward, when you want the time counter to start write something like this:

double start = seconds();

Then, to get the execution time use:

double end = seconds();
double end_2 = end - start;
printf ("\n.:. Computation time : %g seconds\n", end_2);
look at the "About me" page.

Leave a Comment

Your email address will not be published. Required fields are marked *