如何在C中获取一段代码的执行时间?
发布时间:2020-12-16 09:53:07 所属栏目:百科 来源:网络整理
导读:我正在尝试对一段代码进行基准测试.它基于此代码 here,有趣的部分基本上看起来像这样: auto t0 = std::chrono::high_resolution_clock::now(); ... auto t1 = std::chrono::high_resolution_clock::now(); std::cout secs(t1-t0).count() " sn"; 问题是我
我正在尝试对一段代码进行基准测试.它基于此代码
here,有趣的部分基本上看起来像这样:
auto t0 = std::chrono::high_resolution_clock::now(); ... auto t1 = std::chrono::high_resolution_clock::now(); std::cout << secs(t1-t0).count() << " sn"; 问题是我在一台共享机器上,这给了我一些时间,所以我的结果并没有给我任何一致性.我真正需要的是某种秒表工具,它可以让我得到我的代码运行的时间,而不是墙上的时间.有什么选择?如果涉及系统特定的调用,我在Linux机器上,但如果可能的话,我宁愿保持这段代码的可移植性. 我已经看过其他问题,如this和this,但他们似乎都提供壁挂时间解决方案. 解决方法
如果在您的操作系统上可用,您可以使用
times API获得与内置时间命令类似的结果.
#include <sys/times.h> ... struct tms start,end; times(&start); //Do command times(&end); clock_t usr_time = end->tms_utime - start->tms_utime; clock_t sys_time = end->tms_stime - start->tms_stime; 要100%完成,您应检查时间结果是否不等于-1,否则请检查errno代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |