c - 如何测试 C 函数的性能?

标签 c performance function

是否有一些好的方法可以了解函数在 C 中的执行情况?例如,我想将我自己的函数与库函数进行比较。

最佳答案

您需要高分辨率计时器。

在 Linux 上,<a href="http://linux.die.net/man/3/gettimeofday" rel="noreferrer noopener nofollow">gettimeofday()</a>是一个不错的选择,它为您提供微秒分辨率。在 Windows 上,<a href="http://msdn.microsoft.com/en-us/library/ms644904%28VS.85%29.aspx" rel="noreferrer noopener nofollow">QueryPerformanceCounter()</a>是典型的。确保多次运行函数,以获得稳定的读数。

快速示例,适用于 Linux:

struct timeval t0, t1;
unsigned int i;

gettimeofday(&t0, NULL);
for(i = 0; i < 100000; i++)
  function_to_measure();
gettimeofday(&t1, NULL);
printf("Did %u calls in %.2g seconds\n", i, t1.tv_sec - t0.tv_sec + 1E-6 * (t1.tv_usec - t0.tv_usec));

您当然会调整计数 (100,000) 以匹配函数的性能。最好是该函数确实需要一段时间才能运行,否则循环和/或函数调用开销可能会占主导地位。

关于c - 如何测试 C 函数的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1688133/

相关文章:

c - |= 在 C 中意味着什么?

c++ - Linux 应用程序中的架构建议

c - 是 int foo() { return foo();递归函数?

python - 二维 numpy.take 快吗?

function - 如何将可变长度参数作为参数传递给 Golang 中的另一个函数?

c - 如何修复 C 中的自定义 insertString 函数

c - 从 C 或 Delphi 从 Win32 获取 BIOS UUID

c - 在文本文件中搜索 ID (Turbo c)

javascript - javascript静态类继承非静态类的表现

python - python中变量名与程序效率