How can I find the execution time of a section of my program in C?

Stephen Booher picture Stephen Booher · Oct 6, 2008 · Viewed 16.7k times · Source

I'm trying to find a way to get the execution time of a section of code in C. I've already tried both time() and clock() from time.h, but it seems that time() returns seconds and clock() seems to give me milliseconds (or centiseconds?) I would like something more precise though. Is there a way I can grab the time with at least microsecond precision?

This only needs to be able to compile on Linux.

Answer

Andrew Edgecombe picture Andrew Edgecombe · Oct 6, 2008

You referred to clock() and time() - were you looking for gettimeofday()? That will fill in a struct timeval, which contains seconds and microseconds.

Of course the actual resolution is up to the hardware.