Cost of gettimeofday

What is the cost of calling the Linux/Unix system function gettimeofday?

Typically this is considered an expensive operation. However it doesn’t appear to be so, as demonstrated by running the simple test code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <sys/time.h> 
 
#define LOOP 10000000LL
 
/* Save as test.cc, and compile with: g++ -O test.cc
 
   To satisfy ourself that the gettimeofday call is actually being
   invoked, just run the program through strace:
 
   Example:
             $ strace ./a.out
*/
int main(int, const char**)
{
    timeval t0;
    timeval t1;
    timeval* ptr = &t1;
 
    // Time at start
    gettimeofday(&t0, NULL);  // use of the timezone structure is obsolete
 
    unsigned long long int i;
    for (i = 0; i < LOOP; ++i)
    {
        gettimeofday(ptr, NULL);
    }
 
    double t = 1000000.0 * (t1.tv_sec - t0.tv_sec) + t1.tv_usec - t0.tv_usec;
 
    std::cout << "Total elapsed time : " << t/1000000.0 << " sec\n";
    std::cout << "Number of calls    : " << i << "\n";
    std::cout << "Time per call      : " << t / i << " msec\n";
 
    return 0;
}

When compiled with gcc version 4.2.4 on an Intel(R) Core(TM) 2 Duo CPU T7500 2.20GHz Lenovo T61, running Ubuntu 8.04, the quickest observed result is:

Total elapsed time : 12.3674 seconds
Number of calls    : 10000000
Time per call      : 1.23674 microseconds

So that is just over 1 millionth of a second! Considered on its own, this is no time at all. However, whether this is “expensive” or not depends on how frequently gettimeofday is called. For instance, a market data application might receive 5000 price updates each second that each need to be time-stamped; the cumulative cost will exceed 5 milliseconds, and will accrue as latency onto immediately arriving later price ticks.

Leave a Reply