如何测试C函数的性能?

Fre*_*red 5 c performance function

有没有一些很好的方法来了解函数在C中的表现?我想比较一下我自己的函数和库函数.

unw*_*ind 11

你需要高分辨率的计时器.

在Linux上,它gettimeofday()是一个不错的选择,它为您提供微秒级的分辨率.在Windows上,QueryPerformanceCounter()是典型的.确保多次运行您的功能,以获得稳定的读数.

适用于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));
Run Code Online (Sandbox Code Playgroud)

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


小智 5

你好,我会给你一个例子并解释它:

#include <stdio.h>
#include <time.h>

int main(void)
{

    clock_t start_clk = clock();

    /*
        put any code here
    */

    printf("Processor time used by program: %lg sec.\n", \
    (clock() - start_clk) / (long double) CLOCKS_PER_SEC);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:程序使用的处理器时间:4.94066e-324 秒。

时间.h:

声明 clock_t 是一个算术(您可以像我在示例中那样对此值进行数学运算)时间值。基本上把任何代码放在注释所在的地方。

CLOCKS_PER_SEC 是time.h 中声明的一个宏,以它为分母将值转换为秒。

出于两个原因,必须将其强制转换为 long double:

  1. 我们不知道 clock_t 实际上是什么类型,但我们想打印它(你会在 printf 中放入什么转换?)。
  2. long double 是一种非常精确的类型,可以表示非常小的值。


Jef*_*amb 3

进入该功能前请先存储系统时间。从函数返回后存储系统时间。减去差异并比较两个实现。

  • 当然,循环足够多次,以免差异为零。 (2认同)