The gettimeofday
system call (now obsolete in favor of clock_gettime
) is among the shortest system calls to execute. The last time I measured that was on an Intel i486 and lasted around 2us
. The kernel internal version is used to timestamp network packets, read
, write
, and chmod
system calls to update the timestamps in the filesystem inodes, and the like. If you want to measure how many time you spent in gettimeofday
system call you just have to do several (the more, the better) pairs of calls, one inmediately after the other, annotating the timestamp differences between them and getting finally the minimum value of the samples as the proper value. That will be a good aproximation to the ideal value.
Think that if the kernel uses it to timestamp each read
you do to a file, you can freely use it to timestamp each service request without serious penalty.
Another thing, don't use (as suggested by other responses) a routine to convert gettimeofday
result to a string, as this indeed consumes a lot more resources. You can compare timestamps (suppose them t1
and t2
) and,
gettimeofday(&t2, NULL);
if (t2.tv_sec - t1.tv_sec > 86400) { /* 86400 is one day in seconds */
erase_cache();
t1 = t2;
}
or, if you want it to occur everyday at the same time
gettimeofday(&t2, NULL);
if (t2.tv_sec / 86400 > t1.tv_sec / 86400) {
/* tv_sec / 86400 is the number of whole days since 1/1/1970, so
* if it varies, a change of date has occured */
erase_cache();
}
t1 = t2; /* now, we made it outside, so we tie to the change of date */
Even, you can use the time()
system call for this, as it has second resolution (and you don't need to cope with the usecs or with the overhead of the struct timeval
structure).