【发布时间】:2019-10-03 13:46:49
【问题描述】:
我编写了一个 C++ 程序来对各种排序算法进行基准测试,以找出哪一个是最快的。但是,我在执行代码时遇到了一些问题。
我首先创建了一个类来使用构造函数和析构函数对算法进行计时。然后我使用std::chrono::time_point_cast 将时间显式转换为毫秒。但是,每次我运行我的程序时,程序最终都会显示零毫秒。
请注意,我已经包含了 chrono 头文件。
这是涉及的程序源代码部分。
类定义
int Array[20], size = 20;
class BenchmarkTimer
{
public:
std::chrono::time_point<std::chrono::high_resolution_clock> startpt;
float ms;
long long duration;
BenchmarkTimer() : ms(0), duration(0)
{
startpt = std::chrono::high_resolution_clock::now();
}
~BenchmarkTimer()
{
auto endpt = std::chrono::high_resolution_clock::now();
auto init = std::chrono::time_point_cast<std::chrono::milliseconds>(startpt).time_since_epoch().count();
auto final = std::chrono::time_point_cast<std::chrono::milliseconds>(endpt).time_since_epoch().count();
auto duration = final - init;
}
};
选择排序功能(这只是众多排序算法中的一种)。
void SelectionSort(int Array[])
{
BenchmarkTimer timer;
int temp, smallest, position, j;
for (int i = 0; i < size - 1; i++)
{
smallest = Array[i];
position = i;
for (j = i + 1; j < size; j++)
if (Array[j] < smallest)
{
smallest = Array[j];
position = j;
}
temp = Array[i];
Array[i] = Array[position];
Array[position] = temp;
}
DisplayArray(Array);
std::cout << "\nTime taken to sort the array: " << timer.duration << " ms" << std::endl;
}
DisplayArray(Array) 函数调用只是将数组显示在屏幕上。
我希望程序显示经过的毫秒数。
现在,实际输出是:
Time taken to sort the array: 0 ms
但我希望输出是:
Time taken to sort the array: 13 ms
(13 毫秒只是一个例子。)
我建议你建议更简单的解决方案,因为我处于 C++ 编程的中级水平。
提前致谢!
【问题讨论】:
-
是的,我做到了。我什至尝试过使用
nanoseconds。 -
你在析构函数中计算了持续时间,当你调用
timer.duration时析构函数还没有被调用。在一个名为get_elapsed_time()的函数中移动析构函数代码,该函数返回属性duration
标签: c++ visual-studio visual-c++ c++17