C语言 如何轻松地对 C 代码进行基准测试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2349776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I benchmark C code easily?
提问by Mike
Is there a simple library to benchmark the time it takes to execute a portion of C code? What I want is something like:
是否有一个简单的库来对执行一部分 C 代码所需的时间进行基准测试?我想要的是这样的:
int main(){
benchmarkBegin(0);
//Do work
double elapsedMS = benchmarkEnd(0);
benchmarkBegin(1)
//Do some more work
double elapsedMS2 = benchmarkEnd(1);
double speedup = benchmarkSpeedup(elapsedMS, elapsedMS2); //Calculates relative speedup
}
It would also be great if the library let you do many runs, averaging them and calculating the variance in timing!
如果该库让您进行多次运行,对它们进行平均并计算时间差异,那也会很棒!
采纳答案by Joe
Basically, all you want is a high resolution timer. The elapsed time is of course just a difference in times and the speedup is calculated by dividing the times for each task. I have included the code for a high resolution timer that should work on at least windows and unix.
基本上,您只需要一个高分辨率计时器。经过的时间当然只是时间的差异,加速比是通过除以每个任务的时间来计算的。我已经包含了一个高分辨率计时器的代码,它至少应该在 windows 和 unix 上工作。
#ifdef WIN32
#include <windows.h>
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart/(double)f.QuadPart;
}
#else
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
回答by Gaurav
Use the function clock()defined in time.h:
使用中clock()定义的函数time.h:
startTime = (float)clock()/CLOCKS_PER_SEC;
/* Do work */
endTime = (float)clock()/CLOCKS_PER_SEC;
timeElapsed = endTime - startTime;
回答by lhf
回答by Mark Wilkins
There may be existing utilities that help with this, but I suspect most will use some kind of sampling or possibly injection. But to get specific sections of code timed, you will probably have to add in calls to a timer like you show in your example. If you are using Windows, then the high performance timer works. I answered a similar questionand showed example code that will do that. There are similar methods for Linux.
可能有现有的实用程序可以帮助解决这个问题,但我怀疑大多数会使用某种采样或可能的注入。但是要对代码的特定部分进行计时,您可能必须像示例中所示那样添加对计时器的调用。如果您使用的是 Windows,则高性能计时器可以工作。我回答了一个类似的问题,并展示了可以做到这一点的示例代码。Linux 也有类似的方法。

