【问题标题】:Calculate execution time of a function in c++ (visual studio 2010)计算 C++ 中函数的执行时间(Visual Studio 2010)
【发布时间】:2014-02-04 07:26:32
【问题描述】:

我正在使用 c++ 进行编码并使用 Visual Studio 2010。我正在尝试计算函数执行所需的时间,这是我的代码

        double sum=0;   
        clock_t start_s=clock();
        for(int j=1;j<size;j++)
        {
            int key=data[j];
            int i=j-1;
            while(i>=0 && data[i]>key)
            {
                data[i+1]=data[i];
                i=i-1;
            }
            data[i+1]=key;
        }
        clock_t stop_s=clock();
        sum=((double)(stop_s - start_s)/CLOCKS_PER_SEC);

但问题是时间计算为 0。如何以更小的单位测量时间

【问题讨论】:

  • 野兔是你的答案我认为stackoverflow.com/questions/1861294/…
  • visual studio 在“int64”和“uint64”上给出错误
  • 让您测量的东西花费更长的时间是显而易见的选择。如果您测量的内容非常短,您通常会测量可变性。

标签: c++ visual-studio-2010 visual-studio


【解决方案1】:

clock() 将为您提供 1 毫秒的分辨率。 如果您想要更高的分辨率,请使用QueryPerformanceCounter 函数和QueryPerformanceFrequency

【讨论】:

  • 或者,老套路:运行你的代码一百万次:D
【解决方案2】:

一种可能的解决方案是运行此代码段,例如运行 100,000 次,然后计算平均时间

 double sum=0;   
    clock_t start_s=clock();

 int x = 0;

 while (x < 100000)
 {
    for(int j=1;j<size;j++)
    {
        int key=data[j];
        int i=j-1;
        while(i>=0 && data[i]>key)
        {
            data[i+1]=data[i];
            i=i-1;
        }
        data[i+1]=key;
    }      
    x++;
  }
    clock_t stop_s=clock();
    sum=((double)(stop_s - start_s)/CLOCKS_PER_SEC)/100000; //average time

【讨论】:

    【解决方案3】:

    看起来clock() 在 Windows 上返回毫秒分辨率刻度。

    要获得更好的粒度,您应该使用 Windows 高分辨率性能计数器。致电QueryPerformanceFrequencyQueryPerformanceCounter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2015-07-19
      • 2011-02-23
      • 2013-08-01
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多