Hi all,

Here's the problem I have. clock() call returns 0 no matter when I call it....
Code:

#include <time.h>
#include <stdio.h>
#include <math.h>
int main()
{
    volatile double n, i, x;
    clock_t time1, time2, time3;

    int j;
//    while (time1 < 1)
        time1 = clock();
    for (i = 0; i < 100000; i++)
    {
        n = sqrt(i);
        x = n + n;
    }
//    while (time2 < 1)
        time2 = clock();
    for (j = 0; j < 500000; j++)
    {
        n = j*j*j;
        x = n / j;
    }
//    while (time3 < 30000)
        time3 = clock();
    printf("%ld %ld %ld\n", time1, time2, time3);
    return 0;
}

Code compiled with -O0, but output is just 0 0 0. If I uncomment the whiles, it spews out random numbers, something like: 6509390 134518684 30000.

I have a workaround that uses ftime(), but I'm really troubled by the fact that clock() doesn't work. Am I missing something completely obvious here?

By the way, this is on fedora10, gcc compiler.

Thanks

Recommended Answers

All 4 Replies

No guarantees, but I read through this thread and it might shed some light. Of course, it is a C++ thread, but it is on the same exact topic (the OP there also claims the clock is always returning 0). One of the suggestions there is to try to increase the amount of work you're doing and then see what clock outputs. That baffles me a little, since it seems like you are doing a good deal though. Nevertheless, http://www.daniweb.com/forums/thread120862.html

Thanks, I tried something like this:

for (i = 0; i < 5000; i++)
    {
        n = sqrt(i);
        x = n + n;
        printf("%ld\n", clock());
    }
    for (j = 0; j < 50000; j++)
    {
        n = j*j*j;
        x = n / j;
        printf("%ld\n", clock());
    }

and piped the output to a file, and it did seem to work (outputted stuff from 0 to 90000). I guess my original code was completed in under 10000 ticks...
It's a shame that you can't get better resolution than 10ms, although I clearly remember writing a profiling tool a while ago that had single digit resolution of CPU clock...

You never initialize time1, time2, or time3. Perhaps they have random garbage that isn't less than 1. But then why print zero? I don't know, but I like to test values AFTER giving them a value.

I don't know why you're testing the value, anyways.

Yeah sorry. It should have been a do..while instead of a while. I realized that mistake now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.