简体   繁体   English

为什么排序算法需要零秒

[英]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. 除非您使用打孔卡编写程序,否则对10个数字进行排序所花费的时间不会少于一勾,您应该不会感到惊讶。 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. 循环中最里面的指令可以运行100次-与当今的低端处理器相比,这算不了什么。

EDIT: I tested the code with 100000 numbers, that's 10^10 iterations inside the for loop, and it only took 3 seconds. 编辑:我用100000个数字测试了代码,这是for循环内的10 ^ 10次迭代,只花了3秒。

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. 我的计算机用完全相同的起始数组花费0.18秒运行一百万次循环。 Therefore each sort takes about 180 microseconds. 因此,每种排序大约需要180微秒。 This is much too fine to measure with a pair of clock() calls. 这太好了,无法通过一对clock()调用进行测量。

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! 请参阅http://www.songho.ca/misc/timer/timer.html 。您尝试测量的时间在微秒范围内!

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

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