All My Brain Where stuff from my brain lands

June 10, 2008

Timing C/C++ Code on Linux

Filed under: Programming — Tags: , , , — Dennis @ 3:37 pm

For my last post, I played around with C++ and a little programming competition. While on the topic, I decided I’d get slightly more serious and enter the next challenge.

One of the things that slightly annoyed me during the process is having to compile/run the program on Windows to enter the competion, while I’m not opposed to this, I do most of my work during the day on a Linux machine and wanted to be able to use that to develop too. For the most part, this isn’t much of an issue because the code is pretty much standard C++ and is quite cross platform compatible. I just generated a Makefile as well as the Visual Studio Project [1] and I can work on the challenge whenever I feel like devoting a little time.

Anyway, the timer code supplied is not cross platform. It only works on Windows. Since it isn’t that complicated, and I wanted to see times on both platforms, I modified the hr_time.h and hr_time.cpp to include an additional implementation for Linux.

Here are the details:

Linux Time Structures

In <sys/time.h>, you get a few functions and structures that make high resolution timing easy. The gettimeofday function returns the seconds and microseconds since the Epoch. The function operates on the timeval structure:

// snip...
timeval t;
gettimeofday(&t,NULL); // ignoring the 2nd parameter which is the timezone

In addition to being able to query the time, there are also functions for adding, subtracting, and comparing times. For this purpose, the timesub function works perfectly. You need two values (already queried with gettimeofday and and result timeval:

timeval start,stop,result;
// query the start/stop with gettimeofday during your program

result now contains the difference between start/stop in seconds and microseconds.

For the sake of compatibility, the hr_time implementation wants a double for the time, where the fraction part is the number of microseconds. The nice thing is that timesub normalizes tv_usec to somewhere in the range [0,100000). Here is what I did to convert the result to a double:

return result.tv_sec + result.tv_usec/1000000.0; // 1000000 microseconds per second

Here are the completed code files if you’d like to download and look closer or use for yourself:

Have fun coding!

[1] Actually, I used Bakefile to generate the project files.

Powered by WordPress

%d bloggers like this: