【问题标题】:Merge Sort for 10 million inputs [closed]1000万个输入的合并排序[关闭]
【发布时间】:2015-01-29 12:19:20
【问题描述】:

这是我的 C++ 代码。我用过 c++11。用于以微秒为单位测量时间。我的归并排序大约需要 24 秒来对大小为 1000 万的随机生成的数字数组进行排序。但是当我参考我朋友的结果时,他们得到了大约 3 秒。我的代码似乎是正确的,我和他们的不同之处在于他们使用时钟而不是计时来测量时间。这会影响我结果的偏差吗?请回答!

这是我的代码:

#include <iostream>
#include <climits>
#include<cstdlib>
#include<ctime>
#include<chrono>
using namespace std;

void merge_sort(long* inputArray,long low,long high);
void merge(long* inputArray,long low,long high,long mid);

int main(){
    srand(time(NULL));
    int n=1000;
    long* inputArray = new long[n];
    for (long i=0;i<n;i++){   //initialize the arrays of size n with random n numbers
        inputArray[i]=rand();  //Generate a random number
    }
    auto Start = std::chrono::high_resolution_clock::now(); //Set the start time for insertion_sort
    merge_sort(inputArray,0,n); //calling the insertion_sort to sort the array of size n
    auto End = std::chrono::high_resolution_clock::now(); //Set the end time for insertion_sort
    cout<<endl<<endl<<"Time taken for Merge Sort = "<<std::chrono::duration_cast<std::chrono::microseconds>(End-Start).count()<<" microseconds";  //Display the time taken for insertion sort
    delete []inputArray;
    return 0;
}

void merge_sort(long* inputArray,long low,long high){
    if (low<high){
        int mid =(low+high)/2;
        merge_sort(inputArray,low,mid);
        merge_sort(inputArray,mid+1,high);
        merge(inputArray,low,mid,high);
    }
    return;
}

void merge(long* inputArray,long low,long mid,long high){
    long n1 = mid-low+1;
    long n2 = high - mid;
    long *L= new long [n1+1];
    long *R=new long [n2+1];
    for (int i=0;i<=n1;i++){
        L[i] = inputArray[low+i];

    }
    for (int j=0;j<=n2;j++){
        R[j] = inputArray[mid+j+1];
    }
    L[n1]=INT_MAX ;
    R[n2]=INT_MAX;
    long i=0;
    long j=0;
    for (long k=low;k<=high;k++){
        if (L[i] <= R[j] ){
            inputArray[k]=L[i];
            i=i+1;
        }
        else{
            inputArray[k]=R[j];
            j=j+1;
        }
    }

    delete[] L;
    delete[] R;
}

【问题讨论】:

  • 你为什么不使用std::sort ?您在哪个操作系统上运行,使用哪个编译器和哪个优化?另请参阅 this thread 关于 Windows 上不符合标准的 clock 实现...
  • 我认为重点是学习排序算法。但是你的机器和操作系统完全一样吗?尝试运行彼此的代码或尝试更改计时方法,以便获得某种奇偶校验。
  • 我使用的是 Intel i7 处理器,4GB RAM,操作系统是 windows 8 64 位。

标签: performance c++11 mergesort chrono ctime


【解决方案1】:

两次时间测量不可能花费 20 秒。

正如其他人指出的那样,结果实际上取决于平台、编译器优化(调试模式可能比发布模式慢)等等。

如果您的设置与您的朋友相同,但仍然存在性能问题,您可能需要使用分析器来查看您的代码在哪里花费时间。如果您使用的是 linux,则可以使用 that tool,否则 windows 中的 Visual Studio 是一个不错的选择。

【讨论】:

  • 我使用的是 Windows,我使用 Codeblock 作为我的编译器。事情是在 Visual Studio 2010 中它不支持 c++11 标准。所以无法使用chrono
  • 我从未使用过代码块,但您似乎可以通过插件添加探查器,我看到了您可能使用的探查器:wiki.codeblocks.org/index.php?title=Code_Profiler_plugin。否则,如果您只是因为计时而没有使用视觉,您可以使用加速计时器来测量时间,因为它们是便携的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2018-08-01
相关资源
最近更新 更多