- 论坛徽章:
- 0
|
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 |
|