【问题标题】:How to get approximate time, when an algorithm takes zero second/milli-second times?当算法花费零秒/毫秒时间时,如何获得近似时间?
【发布时间】:2016-06-02 16:06:56
【问题描述】:

我需要时间

  • 1000
  • 5000
  • 10000
  • 15000
  • 20000 等编号的数据。

    通过使用 快速排序 算法从 No. 中验证 时间复杂度。的数据时间 图表。但是对于 1000 数据和 20000 数据,我还有 0 秒 时间。如果我以 毫秒或纳秒 为单位测量时间,但时间仍然为零。有什么方法可以为不同的找到近似或比较时间。数据的

我的快速排序流程在这里 -

#include <bits/stdc++.h>
using namespace std;

int A[50000], i, j, V, store;

int part(int left, int right, int P)
{
    V = A[P];
    swap(A[P], A[right]);
    store = left;
    for(i = left; i < right; i++)
    {
        if(A[i] <= V)
        {
            swap(A[i], A[store]);
            store++;
        }
    }
    swap(A[store], A[right]);

    return store;
}

void qSort(int left, int right)
{
    if(left < right)
    {
        j = part(left, right, left);
        qSort(left, j-1);
        qSort(j+1, right);
    }
}

main()
{
    int nData, k, minValue, maxValue;
    cout<<"No. of Data: ";
    cin>>nData;
    cout<<"\nRange (min, max): ";
    cin>>minValue>>maxValue;
    for(k=0; k<nData; k++)
    {
        A[k] = minValue + (rand()%(int) (maxValue - minValue + 1));
    }
    clock_t t1 = clock();
    qSort(0, nData-1);
    clock_t t2 = clock();
    cout<<"\n\nTime: "<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;    
}

[注意:我的操作系统是 Windows]

【问题讨论】:

标签: c++ algorithm time time-complexity quicksort


【解决方案1】:

只需在 for 循环中以足够多的迭代次数重复要测量的任务,然后将测量的时间除以迭代次数。

【讨论】:

  • 可能是一种方式。谢谢H. Guijt
【解决方案2】:
main()
{
    ...
    clock_t t1 = clock();
    qSort(0, nData-1);
    clock_t t2 = clock();
    cout<<"\n\nTime: "<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;    
}

这里的问题是编译器对于这种简单的测试来说太聪明了。编译器看到程序中没有影响的代码,它通过删除不必要的代码来优化程序。您必须禁用优化(在调试模式下运行程序可能会这样做)或修改程序以便以某种方式使用排序操作的结果。

另外,clock() 在 Windows 和 POSIX 系统上具有不同的精度。改用std::chrono 更简单。例如

#include <iostream>
#include <chrono>

int main()
{
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    qSort(0, nData-1);
    end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end - start;
    std::cout << "count:" << elapsed_seconds.count() << "\n";

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多