0

I want to know the time of the quickSort function in my code, I used clock() and it get 0 .. and I also tried to use chrono and it still get me 0 . I also made my array is large . I don't know if my code is wrong or not !

this is my code

#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 Answers1

0

Simple implementation:

#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();
    }
};

Usage:

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";
    }
}
YSC
  • 38,212
  • 9
  • 96
  • 149