我想在C算法上运行一些基准测试,并希望获得所需的cpu时间,具体取决于输入.我在
Windows 7上使用Visual Studio 2012.我已经发现了一种在Windows中计算cpu时间的方法:
How can I measure CPU time and wall clock time on both Linux/Windows?
但是,我在我的算法中使用了system()命令,这不是以这种方式测量的.那么,我如何测量cpu时间并通过system()包含我的脚本调用次数?
我应该添加一个小例子.这是我的get_cpu_time函数(来自上面描述的链接):
double get_cpu_time(){
FILETIME a,b,c,d;
if (GetProcesstimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}else{
// Handle error
return 0;
}
}
到目前为止,这工作正常,当我制作一个程序,对一些数组进行排序(或做一些其他需要一些时间的东西),它工作正常.但是,当我在这种情况下使用system() – 命令时,它不会:
int main( int argc,const char* argv[] )
{
double start = get_cpu_time();
double end;
system("Bla.exe");
end = get_cpu_time();
printf("Everything took %f seconds of cpu time",end - start);
std::cin.get();
}
给定的exe文件的执行以相同的方式测量并且花费大约5秒.当我通过system()运行它时,整个过程需要0秒的cpu时间,这显然不包括exe文件的执行.
一种可能性就是在系统调用上得到一个HANDLE,这有可能吗?
Linux的:
>对于挂钟时间,请使用gettimeofday()或clock_gettime()
>对于cpu时间,请使用getrusage()或times()