天天看點

【算法】測試C++标準庫中sort算法的平均運作時間(C++源碼)

【算法】測試C++标準庫中sort算法的平均運作時間(C++源碼)

  • ​​一、聲明​​
  • ​​二、使用​​
  • ​​三、統計​​
  • ​​四、重複​​
  • ​​五、封裝​​
  • ​​六、源代碼(C++)​​

一、聲明

聲明包含n=100000個整數的vector對象;

二、使用

使用rand()函數為vector中的元素随機指派,要求每一個元素X的取值範圍: 1<=X<=100000;

三、統計

使用sort()函數對上述随機數組進行排序并統計運作時間;

四、重複

重複上述①—③過程100次,然後計算并在螢幕列印sort()排序的平均運作時間;

五、封裝

将計算sort算法平均運作時間的代碼放入一個函數,該函數的簽名為(n為數組大小):void average_time_sort(int n)

六、源代碼(C++)

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
#include<iomanip>
#include<cstdlib>

using namespace std;

int main( )
{
  int j=100;
  double sum=0;
  for(int a=0 ; a<j ; a++)
  {
    srand(time(NULL));
    int n = 100000;
    vector<int>vec(n);
    for(int i = 0 ; i < n; i++)
    {
      vec[i] = rand() % 101 * 1000;
    }
    clock_t start_time = clock();
    sort(vec.begin(),vec.end());
    clock_t elpased_time = clock()-start_time;
    cout<<fixed<<setprecision(6);
    cout<<"Time elapsed:"<<double(elpased_time)/CLOCKS_PER_SEC<<"second."<<endl;
    sum=sum+double(elpased_time)/CLOCKS_PER_SEC;
  }
  cout<<double(sum)/100<<endl;
  getchar();
  return 0;
}      

繼續閱讀