Reputation: 313
The C `clock()` function just returns a zero
clock() function always returning 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
Upvotes: 0
Views: 542
Reputation: 21
My code used enough CPU time. But it seems the clock is only ticking with a step of 15625ms.
My advice is to use <chrono>
instead.
Upvotes: 1
Reputation: 182743
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.
Upvotes: 2