Linux 常见计时系统调用如下:
序号 | 函数 | 类型 | 精度级别 | 时间 |
1 | time | C系统调用 | 低 | <1s |
2 | times | C系统调用 | 低 | <10ms |
3 | clock | C系统调用 | 低 | <10ms |
4 | gettimeofday | linux环境下C系统调用 | 高 | <0.1ms |
Example:
#include <stdio.h>
#include <time.h> /*time, clock*/
#include <sys/times.h> /*times*/
#include <sys/time.h> /*gettimeofday*/
#include <stdlib.h>
#include <unistd.h>
#define COUNT 10000
#define RESOLUTION 1000000.0
/*100*/
long tick_per_sec()
{
return sysconf(_SC_CLK_TCK);
}
int foo()
{
int index = 0;
for(int i = 0; i < COUNT; i++)
{
for(int j = 0; j < COUNT; j++)
{
index++;
}
}
return 0;
}
/*time, resolution: second*/
time_t time_test1()
{
time_t start_time;
time_t elapsed_time;
start_time = time(NULL);
foo();
elapsed_time = time(NULL) - start_time;
printf("time => elapsed time: %f\n", (double)elapsed_time);
return elapsed_time;
}
/*times, resolution: mili second*/
clock_t time_test2()
{
clock_t start_time;
double elapsed_time;
struct tms buf;
start_time = times(&buf);
foo();
elapsed_time = times(&buf) - start_time;
elapsed_time /= tick_per_sec();
//printf("tick_per_sec = %ld\n", tick_per_sec());
printf("times => elapsed time: %fs\n",elapsed_time);
return elapsed_time;
}
/*clock, resolution: mili second
return the CPU time used, to get the number of seconds used, divide by CLOCKS_PER_SEC.*/
clock_t time_test3()
{
clock_t start_time;
clock_t elapsed_time;
start_time = clock();
foo();
elapsed_time = clock() - start_time;
printf("clock => elapsed time: %fs\n", (double)elapsed_time/CLOCKS_PER_SEC);
return elapsed_time;
}
/*gettimeofday, resolution: micro second*/
double time_test4()
{
double elapsed_time;
struct timeval tv1, tv2;
struct timezone tz1, tz2;
gettimeofday(&tv1, &tz1);
foo();
gettimeofday(&tv2, &tz2);
elapsed_time = (tv2.tv_sec + tv2.tv_usec/RESOLUTION) - (tv1.tv_sec + tv1.tv_usec/RESOLUTION);
printf("gettimeofday => elapsed time: %fs\n", elapsed_time);
return elapsed_time;
}
int main(int argc, char* argv[])
{
/*
if(argc != 2)
{
printf("USAGE: binfile number\n");
exit(EXIT_FAILURE);
}
int index = atoi(argv[1]);
*/
time_test1(); //time
time_test2(); //times
time_test3(); //clock
time_test4(); //gettimeofday
}
输出结果:
time => elapsed time: 1.000000
times => elapsed time: 0.310000s
clock => elapsed time: 0.310000s
gettimeofday => elapsed time: 0.317607s
2012. 8. 26