Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

timing

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.

like image 386
Stephen Booher Avatar asked Oct 06 '08 07:10

Stephen Booher


4 Answers

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.

like image 167
Andrew Edgecombe Avatar answered Oct 02 '22 10:10

Andrew Edgecombe


For what it's worth, here's one that's just a few macros:

#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);

Then just use it with:

main() {
  START;
  // Do stuff you want to time
  STOP;
  PRINTTIME;
}

From http://ctips.pbwiki.com/Timer

like image 44
PhirePhly Avatar answered Oct 02 '22 10:10

PhirePhly


You want a profiler application.

Search keywords at SO and search engines: linux profiling

like image 11
Thorsten79 Avatar answered Oct 02 '22 10:10

Thorsten79


Have a look at gettimeofday, clock_*, or get/setitimer.

like image 3
ysth Avatar answered Oct 02 '22 11:10

ysth