尝试测量 C 中函数的执行时间时得到 0

Getting 0 when trying to measure the execution time of function in C

我有一个简单的函数,它接受随机单词并使用插入排序将它们按字典顺序排列 algorithm.I 函数没有问题(它有效,经过测试),但是当我尝试使用测量函数的执行时间时两个不同的 clock() 值,我在函数执行前后得到相同的值,所以它显示 0 作为经过时间

                clock_t t1 = clock();
                InsertionSort(data, n);
                clock_t t2 = clock();

                /*
                * Display the results.
                */

                for (size = i, i = 0; i < size; ++i)
                {
                    printf("data[%d] = \"%s\"\n", (int)i, data[i]);
                }

                /*
                * Display the execution time
                */
                printf("The time taken is.. %g ", (t2 -t1));

这样试试:

#include <sys/types.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>

double gettime(void)
{
   struct timediff td;
   double d=0;
   gettimeofday(&td, NULL);
   d=td.td_usec;
   d+= (double)td.td_usecs / 1000000.;
   return d;
}

double t1=gettime();
InsertionSort(data, n);
printf("%.6f", gettime() - t1);

或者您可能需要像这样更改代码:

 clock_t t1 = clock();
 InsertionSort(data, n);
 clock_t t2 = clock();
 double d= double(t2- t1) / CLOCKS_PER_SEC;

您还可以参考:Easily measure elapsed time

您错误地使用了浮点格式说明符 %g。试试这个

printf("The time taken is.. %u clock ticks", (unsigned)(t2 -t1));

总是假设执行时间长于clock()的粒度。

时间差太小,无法通过此方法测量,无需添加更多代码来执行。 – 风向标

通常,您会想出一种方法来测量您想要计时的大量循环。 10、100、1000,无论产生什么显着的结果。还要记住,在多任务处理 OS 中,每次迭代花费的时间略有不同,因此您还将建立一个典型的 average.The 结果也可能受到处理器缓存的影响 and/or 文件缓存。 – 风向标