Sign in to follow this  
TheMightyDude

clock() returning 0 on Linux

Recommended Posts

Hello All I have a cpp file which is suppose to display a two clock ticks values but it just returns 0 on both. And time() isnt any good due to I need values that update in ms and not in seconds. This is a very basic bit of code:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>

int main (int argc, char **argv)
{
    clock_t start,stop;
    start = clock();
    printf("start: %d\n",(int)start);
    sleep(1);
    stop = clock();
    printf("stop: %d\n",(int)stop);
    return 0;
}
Anyone know why it's doing this? This worked on my old Linux box fine, but not on this one.

Share this post


Link to post
Share on other sites
Quote:
Original post by Null and Void
Not that this actually answers your question, but have you tried an alternative method of time request?

See: What functions are recommended for high precision time retrieval?.

It's worth a shot to see what happens, right? :)


Yup, I had to do some minor code changes but that clock_gettime() worked fine.

Thanks

Paul Kirby

Share this post


Link to post
Share on other sites
Try this and see if it makes a difference:


int main (int argc, char **argv)
{
clock_t start,stop;
start = clock();
printf("start: %llu\n",(unsigned long long)start);
sleep(1);
stop = clock();
printf("stop: %llu\n",(unsigned long long)stop);
return 0;
}

Share this post


Link to post
Share on other sites
clock(3) returns processor time, not wall-clock time. If your test did something useful rather than sleeping, your second call to clock(3) would yield a value greater than zero.

#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 10000000; ++i)
;
printf("took: %fs CPU time\n", (double) clock() / CLOCKS_PER_SEC);
return 0;
}

If you want high precision timers for wall-clock time, take a look at gettimeofday(2) or clock_gettime(2).

Share this post


Link to post
Share on other sites
Quote:

If you want high precision timers for wall-clock time, take a look at gettimeofday(2) or clock_gettime(2).


And make sure to read the manpages all the way, there's interesting stuff about the usefulness of those functions.

Share this post


Link to post
Share on other sites
Also note that OS X doesn't (as of 10.4) have support for clock_gettime. In case you plan on being more portable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this