【发布时间】:2016-08-08 21:37:28
【问题描述】:
我试图弄清楚如何计算我的程序的一部分的执行时间,但是当我使用下面的代码时,我得到的只是 0。我知道这不可能。我正在计时的代码递归地实现了一个大型整数数组的归并排序。如何获得以毫秒为单位执行程序所需的时间?
//opening input file and storing contents into array
index = inputFileFunction(inputArray);
clock_t time = clock();//start the clock
//this is what needs to be timed
newRecursive.mergeSort(inputArray, 0, index - 1);
//getting the difference
time = clock() - time;
double ms = double(time) / CLOCKS_PER_SEC * 1000;
std::cout << "\nTime took to execute: " << std::setprecision(9) << ms << std::endl;
【问题讨论】:
-
clock()只有秒精度(在 32 位系统上它可以每 36 分钟换行一次),所以如果mergeSort()运行时间不到 1 秒,这可以解释为什么你会得到结果0。对于您正在尝试的内容,您需要使用更高精度的计时器,例如来自clock_gettime(),甚至是特定于操作系统的 API。