【问题标题】:Get the running time of a function in c++获取c++中函数的运行时间
【发布时间】:2014-02-05 20:42:22
【问题描述】:

我想为我的作业计算一个函数的运行时间。我一直得到 0 坚果,我的老师严格说他想要一些非零值,即使是 10 大小的循环也是如此。到目前为止我的代码是这样的

#include <chrono>

using namespace std;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::chrono::steady_clock;

steady_clock::time_point t1 = steady_clock::now();
for(int i=0;i<times;i++){
    bubbleSort(arr,size);
}
steady_clock::time_point t2 = steady_clock::now();
cout<<(float)duration_cast<nanoseconds>(t2-t1).count()/times<<"     ";

我也尝试过 chrono::high_resolution_clock 、 clock() 和许多其他人。 主要问题是我必须为time=1; and size=10 提供一些非零值。 请建议我该怎么做?

【问题讨论】:

  • 您无法测量小于时钟分辨率的时间。
  • Alex 所说的,也可以试试high_resolution_clock,以防steady_clock 在您的操作系统中分辨率不是很高。
  • bubbleSort 函数中有一个嵌套循环。即使是简单的cout&lt;&lt;"Hello Worl\n"; 也会给出一些非零值。我不明白 cout 如何比嵌套循环和检查条件花费更多时间
  • @vanza 我都试过了
  • 执行一个完整函数所花费的时间stackoverflow.com/a/40380118/6180077

标签: c++ time performance-testing


【解决方案1】:

我尝试运行您的代码,当然注释了 bubbleSort 部分。它给出了一些非零值。试试这个:

cout<<(float)duration_cast<nanoseconds>(t2-t1).count()/(float)times<<"     ";

【讨论】:

  • @SSMA 你用的是什么编译器?是 Visual Studio 吗?
  • 是的 Visual Studio 2012
  • @SSMA ,尝试在compileonline.com/compile_cpp11_online.php运行您的代码
  • @SSMA Visual Studio 在 C++11 日期和时间方面存在问题。大约一年前,有同样问题的人发布了一个问题,但我现在找不到。
  • @Wajahat 感谢您的建议。它在 compileonline.com 上工作。但是有没有办法让它在 Visual Studio 上工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多