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

3
  • Hare is You Answer i think stackoverflow.com/questions/1861294/… Commented Feb 4, 2014 at 7:28
  • visual studio gives error on "int64" and "uint64" Commented Feb 4, 2014 at 7:31
  • 1
    Make the thing you measure take longer is the obvious option. If what you measure is very short you will nostly measure variability. Commented Feb 4, 2014 at 7:32

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or, the hacky way: run your code a million times :D
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 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.