常用的计时函数
在日常的工作过程中,时常会遇到需要计时的要求,不同场合需要的计时精度也不同,这里列举几个常用的计时函数,以备不时之需。
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\n", 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\n", (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\n", (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\n", 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\n",diff/1000000); return 0; }
以上5个函数是我曾经使用过的与计时相关的函数,其中1、2是C提供的标准函数,3、4是Windows系统提供的,5是Linux系统的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具