gettimeofdayとclock_gettimeの違い


clock_gettimeはgettimeofdayより正確です
簡単にテストをしました
まずclock_を使いますgettimeテストをしてみましょう
test.c #include<time.h>
#include<stdio.h>

#define MILLION 1000000

int main(void)
{
        struct timespec tpstart;
        struct timespec tpend;
        long timedif;

        clock_gettime(CLOCK_MONOTONIC, &tpstart);
        clock_gettime(CLOCK_MONOTONIC, &tpend);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        fprintf(stdout, "it took %ld microseconds/n", timedif);

        return 0;
}


linux 2.6カーネルの下
gcc -o test test.c -lrt
./test
結果:
it took 2 microseconds
今gettimeofdayでテストをします#include<time.h>
#include<stdio.h>

#define MILLION 1000000

int main(void)
{
        struct timespec tpstart;
        struct timespec tpend;
        long timedif;

        gettimeofday(&tpstart, NULL);
        gettimeofday(&tpend, NULL);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        fprintf(stdout, "it took %ld microseconds/n", timedif);

        return 0;
}

gcc -o test test.c 
./test
結果:
it took 0 microseconds
 
AIX以下でも同様の結果が得られた
そしてclock_を通過することができますgettimeこの関数は64ビットプログラムが32よりプログラムの実行が速いことをテストします
AIX P 570,16個のCPU 15.5 Gメモリマシンでテストした
64ビットモードで得られた結果は0 microsecondsであった.
32ビットモードで得られた結果は1 microsecondであった.