用vector实现对10W个随机数进行插入排序为什么这么慢?
在visual studio 2008下编译速度巨慢,要300多秒
而用intel c++ compiler编译就快了很多倍,只需要10秒左右
另外改成用数组实现也要快很多,不到20秒
请高手指点一下是什么原因?按道理说用数组和用vector,时间差距不应 该这么大啊
一开始以为是vector要做越界检查的原因,在程序开头加了#define _SECURE_SCL 0还是很慢
下面是源代码:
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string>
int main()
{
int vectorSize;
cout<<"Please enter the size of vector: ";
cin>>vectorSize;
cout<<endl;
vector<float> v1; //the vectors to store the numbers to be sorted
srand(time(NULL)); // to generate differnt numbers for sort each time
//Initialize the vector v
for(int i=0;i<vectorSize;i++)
{
float rNum; //random number
rNum=(float)rand()/RAND_MAX; //generate random numbers
v1.push_back(rNum); //insert rNum into the vector v1
}
clock_t start,end; //starting time and ending time
start=clock();
insertionSort(v1);
end=clock();
cout<<float) (end-start)/ CLOCKS_PER_SEC <<" secs"<<endl;
return 0;
}
void insertionSort(vector<float>& v)
{
float temp;
for(int i=1;i< v.size();i++)
{
//v[0...i-1] is a sorted subarray
//find a correct postion for v[i] and insert v[i] to it
int j=i;
temp=v[i];
while(j>0&&temp<v[j-1])
{ //move the numbers that are greater than v[i]
v[j]=v[j-1];
j--;
}
v[j]=temp; //find the right postion and assign v[i] to it
}
}