tags:

views:

700

answers:

7

Hi there,

I am looking for a fast way to get the elapsed time between two calls of a function in C.

I considered using jiffies, but they are not available in userland. So, should I use getimeofday() or is there any fastest way to do this.

I am only interested in the elasped time between two calls, to use in a benchmark tool.

+2  A: 

If you're on an x86/x64 architecture, and you're running on a single CPU, you might consider reading the time-stamp counter on the CPU to get a cycle-count. Wikipedia has more information. Note that this approach is less useful if your application is running on multiple CPUs, since each CPU will have its own TSC. Also be wary of frequency scaling if you decide that you want to convert cycles -> time units.

greg
+1 for RDTSC...
dmityugov
+2  A: 

Yes, gettimeofday() would suffice if you want to find the actual elapsed. If you need to find the CPU time, then you can use clock(). In many cases, both approach would give similar result (unless there is a sleep or some sort of wait in code). An example of clock() can be found here:
http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library%5F19.html

swatkat
+3  A: 

Take a look at clock_gettime, which provides access to high-resolution timers.

Martin B
clock_gettime() with the CLOCK_MONOTONIC source is preferred to do relative timing. gettimeofday() is prone to error if a user or process can change the current time.
KFro
+3  A: 

I'd get the processor time via clock() from time.h. To get useful values, convert to milliseconds via CLOCKS_PER_SEC:

clock_t start = clock();
// [...]
clock_t end = clock();
unsigned long millis = (end - start) * 1000 / CLOCKS_PER_SEC;
Christoph
A: 

Thanks guys clock() seems a little tricky to use, especially in SMP environnement (I can't garantee the process won't get migrated from a cpu to another)

My test show a difference of about 30% between the time to call clock() and the time to call gettimeofday(). I think I will stick to this last one and modify my code to call it less often.

A: 

If your kernel supports gettimeofday() as a vsyscall (virtual system call), then using this will be faster than calling a regular system call such as clock(). See Andrea Arcangeli's presentation for some information on how vsyscalls work.

mark4o
A: 

Bit of a late addition, however the time uility available on any linux/unix may be a lighter weight way of achieving what you want. Here are 2 examples

time ls -l stuff*
ls: stuff*: No such file or directory
    0.01s real     0.00s user     0.00s system


 time -c run_script.csh` 

...

real    1m22.38s
user    0m14.67s
sys     0m1.06s
Wiretap