Category: Other stuff

High speed timing in C

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));
Something in my past

Something in my past

For my sins I used to write the About C, C++ and C# website for About .com between 2006 and 2013. There were tutorials, programming contests, curated libraries and the SDL 1 version of Asteroids without the pixel perfect collision detection.  Many of those articles (but not all) are now on the Thoughtco website. I’ll try and dig up some of the older stuff from here.