gettimeofday和clock_gettime的不同

时间:2022-09-06 14:13:29

http://www.9php.com/FAQ/cxsjl/c/2007/12/0405444108599.html

2007-12-21 16:54ovipgdft

clock_gettime比gettimeofday更加精确
简单做了一下测试
#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
#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

2007-12-21 17:02ovipgdft

AIX下面也得到同样的结果
而且可以通过clock_gettime这个函数测试出64位程序要比32为程序运行快
在AIX P570,16个CPU 15.5G内存机器上测试了一把
用64位模式得到的结果是 0 microseconds
用32位模式得到的结果是 1 microsecond