简体   繁体   中英

why sorting algorithm takes zero seconds

here is algorithm

#include<iostream>
#include<Windows.h>
#include<time.h>
using namespace std;
int main(){
    int a[10]={12,3,5,2,7,80,10,1,16,30};
    long ts,te;
    srand(::GetTickCount());
    ts=clock();
     for (int i=0;i<10;i++){
       for (int j=9;j>i;j--){

                  if (a[j]<a[j-1]){

                   int t=a[j];a[j]=a[j-1];a[j-1]=t;

                  }

       }



     }

       te=clock();
       cout<<" time elapsed "<<te-ts<<endl;




 return 0;
}

but i am surprise ,because it gives me zero as output,i am measuring time elapsed from begining of code to finishing,and why?my computer is not so called supercomputer and what is wrong in this code fragment?

Unless you used punch-cards to write your program, you shouldn't be surprised that sorting 10 numbers takes less than one tick. If you want a more accurate profile of your code, use milliseconds, that should give you a better idea.

The inner-most instruction in the loops run 100 times - that's nothing compared to even a low-end processor nowadays.

EDIT: I tested the code with 100000 numbers, that's 10^10 iterations inside the for loop, and it only took 3 seconds.

You should not be surprised that sorting ten numbers takes less than one tick of the clock. Repeat the sorting many times to get meaningful timings.

My computer takes 0.18 seconds to run 1 million repetitions of your loop with with the exact same starting array. Therefore each sort takes about 180 microseconds. This is much too fine to measure with a pair of clock() calls.

You can get more accurate time measurment using a high resolution timer. see http://www.songho.ca/misc/timer/timer.html The time you're trying to measure leaves in the ranges of microseconds!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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