High speed timing in C

One of the things I like doing is timing code. Not to benchmark it per se, but to get an idea of performance. I have a small set of functions to do this on most CPUs for the last ten or fifteen years. It uses the high frequency clock, which. on my PC (a five year old I7-5930K), this counts at the rate of 3,500,000,000 per second.

You just read this timer twice, subtract the difference and then divide by the frequency (3500,000,000) to get a time in fractions of a second accurate to nano-seconds. (10-9 seconds).

Here’s the code for Windows. It’s in the several of the ebook chapters, e.g. chapter 48 (download the file asteroids_ch48.zip and unzip) . Or you can just copy from here.

hr_time.h

#include <windows.h>

typedef struct {
LARGE_INTEGER start;
LARGE_INTEGER stop;
} stopWatch;

void startTimer(stopWatch *timer);
void stopTimer(stopWatch *timer);
double LIToSecs(LARGE_INTEGER * L);
double getElapsedTime(stopWatch *timer);

and hr_time.c

#include 

#ifndef hr_timer
#include "hr_time.h"
#define hr_timer
#endif

void startTimer(stopWatch *timer) {
QueryPerformanceCounter(&timer->start);
}

void stopTimer(stopWatch *timer) {
  QueryPerformanceCounter(&timer->stop);
}

double LIToSecs(LARGE_INTEGER * L) {
  LARGE_INTEGER frequency;
  QueryPerformanceFrequency(&frequency);
return ((double)L->QuadPart / (double)frequency.QuadPart);
}
double getElapsedTime(stopWatch *timer) {
LARGE_INTEGER time;
  time.QuadPart = timer->stop.QuadPart - timer->start.QuadPart;
return LIToSecs(&time);
}

Use it like this:

stopWatch s; // declare a stopwatch variable

startTimer(&s);

// your code to be timed here

stopTimer(&s);

printf('It took %10.6f secs',getElapsedTime(&s));
(Visited 21 times, 1 visits today)