简体   繁体   English

在c ++中计算函数的执行时间(visual studio 2010)

[英]Calculate execution time of a function in c++ (visual studio 2010)

I am coding in c++ and working on Visual Studio 2010. I am trying to compute the time that a function takes to execute, here is my code 我正在使用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);

but the problem is that the time computes to 0. How can I measure the time in even smaller unit 但问题是时间计算为0.如何以更小的单位测量时间

The clock() will give you a resolution of 1 ms. clock()将为您提供1 ms的分辨率。 If you want a higher resolution, use the QueryPerformanceCounter function, and QueryPerformanceFrequency 如果您想要更高的分辨率,请使用QueryPerformanceCounter函数和QueryPerformanceFrequency

One possible solution is to run this code segment, say for 100,000 times then calculate the average time 一种可能的解决方案是运行此代码段,比如说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

It looks like clock() is returning millisecond resolution ticks on Windows. 看起来clock()在Windows上返回毫秒级分辨率。

To get better granularity you should use the Windows high-resolution performance counter. 要获得更好的粒度,您应该使用Windows高分辨率性能计数器。 Call QueryPerformanceFrequency and QueryPerformanceCounter . 调用QueryPerformanceFrequencyQueryPerformanceCounter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM