有时我们需要评价一个算法性能,那么算法的执行时间便是一个不可忽视的因素,而由于某种特殊的需求,我们需要算法的执行时间尽可能地精确,linux下就提供了这样的一个函数:clock_gettime。该函数提供的可是提供了纳秒的精确度。
函数的原型如下:
int clock_gettime(clockid_t clk_id, struct timespect *tp);
clockid_t clk_id用于指定计时时钟的类型,对于我们Programmr以下三种比较常用:
CLOCK_REALTIME, a system-wide realtime clock.
CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.
CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.
CLOCK_REALTIME, a system-wide realtime clock.
CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.
CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.
struct timespect *tp用来存储当前的时间,其结构如下:
1 struct timespec {
2 time_t tv_sec; /* seconds */
3 long tv_nsec; /* nanoseconds */
4 };
测试代码:
#include <stdio.h> #include <time.h>
struct timespec diff(struct timespec start,struct timespec end) { struct timespec temp; if((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000 + end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; }
int main() { struct timespec time1,time2,temp; int i; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); for(i=0; i<10000;i++) { ; } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2); temp = diff(time1, time2); printf("%d:%d\n", temp.tv_sec, temp.tv_nsec); return 0; }
|
这里需要注意一点的就是,编译时需要链接lrt库,否则会提示找不到clock_gettime函数,
[root@localhost ~]# gcc timetest.c -o timetest -lrt