在日常的工作过程中,时常会遇到需要计时的要求,不同场合需要的计时精度也不同,这里列举几个常用的计时函数,以备不时之需。
1、time()
头文件:time.h
原型:time_t time(time_t *tloc)
精度: <1s
精度级别:低
示例:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char* argv[]) { time_t now; now = time(NULL); printf("%s %ju secs since the Epoch ", asctime(localtime(&now)), now); system("pause"); return 0; }
2、clock()
头文件:time.h
原型:clock_t clock(void)
说明:返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,与 CLOCKS_PER_SEC(#define CLOCKS_PER_SEC ((clock_t)1000))有关,
精度:<10ms
精度级别:低
示例:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char* argv[]) { clock_t start, end; long long i = 0; start = clock(); while (i < 10000000000) ++i; end = clock(); printf("耗时:%ds ", (end - start) / CLOCKS_PER_SEC); system("pause"); return 0; }
3、timeGetTime()
头文件:timeapi.h
原型:DWORD timeGetTime(void)
精度: <1ms
精度级别:中
示例:
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <timeapi.h> #pragma comment(lib, "winmm.lib ") int main(int argc, char* argv[]) { DWORD start, end; start = timeGetTime(); Sleep(1); end = timeGetTime(); printf("耗时:%ds ", (end - start)); system("pause"); return 0; }
4、QueryPerformanceCounter()
头文件:profileapi.h
原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency)
精度: <0.1ms
精度级别:高
示例:
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <profileapi.h> int main(int argc, char* argv[]) { LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nBeginTime); Sleep(1000); QueryPerformanceCounter(&nEndTime); double diff = (double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart; printf("耗时:%fs ", diff); system("pause"); return 0; }
5、gettimeofday()
头文件:sys/time.h
原型:int gettimeofday(struct timeval *tv, struct timezone *tz);
精度: <0.1ms
精度级别:高
示例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> int main(int argc,char* argv[]) { struct timeval start; struct timeval end; double diff; gettimeofday(&start,NULL); sleep(1); gettimeofday(&end,NULL); diff = (end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec); printf("%fs ",diff/1000000); return 0; }
以上5个函数是我曾经使用过的与计时相关的函数,其中1、2是C提供的标准函数,3、4是Windows系统提供的,5是Linux系统的