2

I want the exact time to run a program, I use it from clock(). But there is a problem that I can not give an exact time for small n like 2000.

I want it to return the correct answer for n=1000.

#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;

#define show_time(x, y) cout << endl << #x << " : " << y << endl;

int main()
{
    int n;
    cin >> n;
    int *a = new int[n];

    for(int i=0; i<n; i++)
        a[i] = i;
    random_shuffle(a, a+n);
    int last = clock();

    //STL_sort:
    sort(a, a+n);
    int lastP = clock();

    show_time(STL_sort, (double)(lastP-last)/CLOCKS_PER_SEC);
    return 0;
}

The output is 0. (Definitely 0 will not be the answer)

1 Answers1

4

What platform are you running on? If you're on Windows, you could try the high-resolution time library.

If you have access to C++11, there is a header called chrono that has similar functionality, and is portable (ish)!

anjruu
  • 1,224
  • 10
  • 24
  • Why that *-ish* about `chrono` portability? – Vittorio Romeo Oct 31 '13 at 13:56
  • 3
    Because std::chrono::high_resolution_clock uses the highest resolution timer available, so while the header and class are portable, the exact resolution may vary between systems. – anjruu Oct 31 '13 at 13:57
  • 2
    @VittorioRomeo: Not to mention that it was added recently enough that there are still quite a few compilers in relatively wide use that either don't have it at all or don't implement it entirely correctly. – Jerry Coffin Oct 31 '13 at 14:17