Christian Roberts
Christian Roberts

Reputation: 1

Getting time elapsed in a C program using clock()

I've been trying to measure time elapsed in a C program using the clock function, but whenever I try to printf any clock values I'm getting back 0. For example:

    clock_t time1, time2;
    time1 = clock();
    printf("Time 1 is %d.\n", (int)time1);
    sleep(2);
    time2 = clock();
    printf("Time 2 is %d.\n", (int)time2);

In both cases, time1 and time2 print out as 0. I have a feeling it's because I'm using the wrong type in the printf, but every type I've seen doesn't seem to work for me. I've used %Lf, %ld, %f. Can anyone else spot a problem here?

EDIT: I tried most of the types mentioned in this thread: What’s the correct way to use printf to print a clock_t? I even tried uintmax_t, but without the ability to print p1 and p2, I don't know how to verify if it's a type issue or if clock isn't returning the adequate value.

Upvotes: 0

Views: 958

Answers (1)

evading
evading

Reputation: 3090

From cplusplus.com

Clock program Returns the processor time consumed by the program.

The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).

The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.

Basically if your computation time is too small you won't notice anything.

Try adding a while loop from 0 to something big and increment a volatile variable inside it before calling clock() a second time.

Upvotes: 1

Related Questions