c++代码执行定时器返回0,需要以毫秒为单位输出
c++ code execution timer returning 0, need output in milliseconds
我试图弄清楚如何为我的部分程序的执行计时,但是当我使用以下代码时,我得到的所有结果都是 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;
您可以使用 C++11 中的 chrono 库。以下是修改代码的方法:
#include <chrono>
//...
auto start = std::chrono::steady_clock::now();
// do whatever you're timing
auto end = std::chrono::steady_clock::now();
auto durationMS = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "\n Time took " << durationMS.count() << " ms" << std::endl;
如果您在 OSX 上进行开发,来自 Apple 的 blog post 可能会有用。它包含的代码片段应该可以为您提供所需的时间分辨率。
我试图弄清楚如何为我的部分程序的执行计时,但是当我使用以下代码时,我得到的所有结果都是 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;
您可以使用 C++11 中的 chrono 库。以下是修改代码的方法:
#include <chrono>
//...
auto start = std::chrono::steady_clock::now();
// do whatever you're timing
auto end = std::chrono::steady_clock::now();
auto durationMS = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "\n Time took " << durationMS.count() << " ms" << std::endl;
如果您在 OSX 上进行开发,来自 Apple 的 blog post 可能会有用。它包含的代码片段应该可以为您提供所需的时间分辨率。