Frank Buss
Frank Buss

Reputation: 722

times and CLOCK_PER_SEC calculates the wrong time

I have a problem with this program:

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h>  
#include <stdlib.h>  
#include <string.h> 
#include <time.h> 
#include <sys/time.h>
#include <sys/times.h>

clock_t start_time;

clock_t get_user_ticks()
{
    struct tms t;
    times(&t);
    return t.tms_utime;
}

void start_stopwatch()
{
    start_time = get_user_ticks();
}

void stop_stopwatch()
{
    clock_t stop_time = get_user_ticks();
    double ticks = stop_time - start_time;
    double s = ticks / CLOCKS_PER_SEC;
    printf("elapsed time: %fs\n", s);
}

int main(int argc, char** argv) 
{
    start_stopwatch();
    int sum = 0;
    for (long i = 0; i < 1000000000; i++) {
        sum += i;
    }
    printf("sum: %i\n", sum);
    stop_stopwatch();

    return 0;
}

When I compile and execute it like this: gcc -O0 test.c ; time ./a.out I get the following output:

sum: -1243309312
elapsed time: 0.000250s

real    0m2.509s
user    0m2.508s
sys     0m0.000s

Why is the output of my program by a factor of 10000 wrong? And how can I get higher precision as with the time command?

Tested on Debian Buster, 64 bit, with gcc version 8.3.0.

Upvotes: 0

Views: 124

Answers (1)

KamilCuk
KamilCuk

Reputation: 140890

Well, because CLOCKS_PER_SEC is wrongly used here. CLOCKS_PER_SEC is to convert the return value of clock() to seconds. But... note the posix times docs:

Applications should use sysconf(_SC_CLK_TCK) to determine the number of clock ticks per second as it may vary from system to system.

The man 2 times also mentions this in NOTES section.

Do:

double s = ticks / sysconf(_SC_CLK_TCK);

And how can I get higher precision as with the time command?

Use getrusage. Also see bash sources of time command.

Upvotes: 1

Related Questions