clock_gettime() 用来测量处理时间 ( struct timespec )
没什么难理解的地方, 混个脸熟,主要就是看diff() 函数是怎样计算差值的用clock_gettime() 处理前调用一次,
处理后调用一次来计算差值
程序代码:
#include <time.h> #include <stdio.h> #include <stdlib.h> struct timespec diff( struct timespec start, struct timespec end); int main(void) { struct timespec start, end, result; int temp, i; /*开始调用一次*/ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for( i = 0; i < 242000000; i++) temp += temp; /*结束调用一次*/ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); result = diff( start, end); printf("Process time: %lu tv_sec, %lu tv_nsec\n", result.tv_sec, result.tv_nsec); } struct timespec diff( struct timespec start, struct timespec end) { struct timespec temp; /*这种情况下高位借1秒给tv_nsec*/ 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; }
用 gcc 编译的时候加上 -lrt 选项
[ 本帖最后由 madfrogme 于 2012-8-30 17:40 编辑 ]