0

The C `clock()` function just returns a zero

clock() function always returning 0

why C clock() returns 0

I looked up all these questions and answers

And I learned that clock() returns clock ticks per some constant which differs per systems

And time() returns the number of seconds.

First, I was trying to measure the execution time of my sorting algorithm using clock() like this:

#include <iostream>
#include <ctime>

... Some other headers and codes

a = clock();
exchange_sort();
a = clock() - a;

... Rest of the code

I tried many different data types with a like int, clock_t, long, float. And I sorted a pretty big size array int arr[1000] with already increased order. But the value of a was always 0, so I tried to find the reason using gdb and I set a breakpoint to the line where the sorting algorithm is located so that I can check the value of a = clock(); and there has to be some number inside the variable but there was only 0.

So after that, I tried to check whether the function was the problem itself or something else like this:

#include <iostream>
#include <iostream>

int main()
{
    int a;
    clock_t b;
    float c;
    long d;
    a = clock();
    b = clock();
    c = clock();
    d = clock();
    return 0;
}

And I checked the value of each variable through gdb and there were just garbage numbers before I put the return value of clock() but after I put there were only 0s inside the variables. So apparently clock() just returns 0 all the time in my conclusion

I really don't know how can I fix this

My g++ version is 4.4.7. I ran this in Linux My processor is x86_64-redhat-linux

TYFA
  • 313
  • 1
  • 10
  • 2
    possibly answered here: https://stackoverflow.com/questions/27178789/c-different-implementation-of-clock-in-windows-and-other-os – Lock-not-gimbal Mar 31 '19 at 11:46
  • 1
    I would recommend using [std::chrono](https://en.cppreference.com/w/cpp/chrono) instead and getting yourself a more modern compiler (for example by installing [devtoolset-8](https://access.redhat.com/documentation/en-us/red_hat_developer_toolset/8/html/8.0_release_notes/dts8.0_release)). – Jesper Juhl Mar 31 '19 at 12:49
  • 1
    @Lock-not-gimbal thanks for the clue! I should read that in detail – TYFA Mar 31 '19 at 14:41
  • @JesperJuhl I just knew about the function! Thanks – TYFA Mar 31 '19 at 14:43
  • Possible duplicate of [C: Different implementation of clock() in Windows and other OS?](https://stackoverflow.com/questions/27178789/c-different-implementation-of-clock-in-windows-and-other-os) – Armali Apr 01 '19 at 07:36

2 Answers2

2

The clock() function is a coarse measure of CPU time used. Your code doesn't use enough CPU time to measure with such a coarse measure. You should probably switch to something like getrusage instead.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

My code used enough CPU time. But it seems the clock is only ticking with a step of 15625ms.Elapsed time

My advice is to use <chrono> instead.