【发布时间】:2013-06-30 05:29:28
【问题描述】:
我的意思是:如何测量 CPU 用于函数执行的时间以及运行函数所需的挂钟时间? (我对 Linux/Windows 以及 x86 和 x86_64 都感兴趣)。看看我想做什么(我在这里使用 C++,但我更喜欢 C 解决方案):
int startcputime, endcputime, wcts, wcte;
startcputime = cputime();
function(args);
endcputime = cputime();
std::cout << "it took " << endcputime - startcputime << " s of CPU to execute this\n";
wcts = wallclocktime();
function(args);
wcte = wallclocktime();
std::cout << "it took " << wcte - wcts << " s of real time to execute this\n";
另一个重要问题:这种时间测量架构是否独立?
【问题讨论】:
-
我知道您想在代码中以编程方式执行此操作,但无论如何:superuser.com/questions/228056/…
-
@Huytard: 谢谢:) 我知道
time在 linux 但正如你所写,我需要直接在 C 代码中完成 -
@yak 在 Windows 上,
clock()提供挂墙时间,GetProcessTimes提供 cpu 时间。在 Linux 上,gettimeofday()提供了挂墙时间,clock()提供了 cpu 时间。 -
@Mysticial:嗯!所以它有点复杂!稍后我将尝试编写一些代码并粘贴结果(对于win/lin)。但欢迎任何其他答案! :)
-
如果你会使用 C++,
boost::auto_cpu_timer(boost.org/libs/timer) 就是你所需要的。你的代码变成了boost::auto_cpu_timer t; function(args);(是的,没有cout,没什么,就是这样,你得到了wall和cpu——我喜欢这个功能)。
标签: c++ c performance time cpu