如何计算函数的时间?

时间:2016-03-15 14:51:23

标签: c++ algorithm sorting time

我想知道我的代码中quickSort函数的时间,我使用clock()并且它得到0 ..我也尝试使用chrono它仍然得到0。 我也让我的阵列很大。 我不知道我的代码是否错误!

这是我的代码

#include <iostream>
#include <chrono>
#include <ctime>
#include <ratio>

using namespace std;
using namespace chrono;

void quick_sort(int *arr,int left,int right){

    int i=left,j=right;
    int pivot=arr[(left+right)/2];
    while(i<=j){
        while(arr[i]<pivot)
            i++;
        while(arr[j]>pivot)
            j--;
        if(i<=j){
            swap(arr[i],arr[j]);
            i++;
            j--;
        }
    }
    if(left<j)
        quick_sort(arr,left,j);

    if(right>i)
        quick_sort(arr,i,right);


}


int main()
{
  int arr[30]={4,2,5,3,8,9,7,10,54,23,65,78,10,44,56,91,75,79,42,81,10,57,23,651,78,100,47,50,71,715};
  high_resolution_clock::time_point t1 = high_resolution_clock::now();
  quick_sort(arr,0,29);
  high_resolution_clock::time_point t2 = high_resolution_clock::now();
  duration<double>time_span = duration_cast<duration<double> >(t2-t1);
  cout<<"it takes "<<time_span.count()<<" seconds"<<endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

简单实施:

#include <iostream>
#include <iomanip>
#include <string>

// benchmak
#include <limits>
#include <random>
#include <chrono>
#include <algorithm>
#include <functional>
class Clock
{
    std::chrono::time_point<std::chrono::steady_clock> _start;

public:
    static inline std::chrono::time_point<std::chrono::steady_clock> now() { return std::chrono::steady_clock::now(); }

    Clock() : _start(now())
    {
    }

    template<class DurationUnit>
    std::size_t end()
    {
        return std::chrono::duration_cast<DurationUnit>(now() - _start).count();
    }
};

<强>用法

int main()
{
    {
        Clock clock;
        business();
        const double unit_time = clock.end<std::chrono::nanoseconds>();
        std::cout << std::setw(40) << "business(): " << std::setprecision(3) << unit_time << " ns\n";
    }
}