0

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

        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

user2969426
  • 119
  • 1
  • 10

3 Answers3

1

The clock() will give you a resolution of 1 ms. If you want a higher resolution, use the QueryPerformanceCounter function, and QueryPerformanceFrequency

RawBean
  • 412
  • 5
  • 19
1

One possible solution is to run this code segment, say for 100,000 times then calculate the average time

 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
Varo
  • 821
  • 1
  • 7
  • 15
0

It looks like clock() is returning millisecond resolution ticks on Windows.

To get better granularity you should use the Windows high-resolution performance counter. Call QueryPerformanceFrequency and QueryPerformanceCounter.

David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389