How can I get the execution time of a program in milliseconds in C?

alex picture alex · Feb 7, 2010 · Viewed 21k times · Source

Currently I'm getting the execution wall time of my program in seconds by calling:

time_t startTime = time(NULL);
//section of code
time_t endTime = time(NULL);
double duration = difftime(endTime, startTime);

Is it possible to get the wall time in milliseconds? If so how?

Answer

Jonathan Leffler picture Jonathan Leffler · Feb 7, 2010

If you're on a POSIX-ish machine, use gettimeofday() instead; that gives you reasonable portability and microsecond resolution.

Slightly more esoteric, but also in POSIX, is the clock_gettime() function, which gives you nanosecond resolution.

On many systems, you will find a function ftime() that actually returns you the time in seconds and milliseconds. However, it is no longer in the Single Unix Specification (roughly the same as POSIX). You need the header <sys/timeb.h>:

struct timeb mt;
if (ftime(&mt) == 0)
{
     mt.time ... seconds
     mt.millitime ... milliseconds
}

This dates back to Version 7 (or 7th Edition) Unix at least, so it has been very widely available.

I also have notes in my sub-second timer code on times() and clock(), which use other structures and headers again. I also have notes about Windows using clock() with 1000 clock ticks per second (millisecond timing), and an older interface GetTickCount() which is noted as necessary on Windows 95 but not on NT.