Antonio Marramao
Antonio Marramao

Reputation: 13

Function clock() in C

While studying the clock () function located in time.h, I asked myself the question of making a simple program to see how it worked. I was surprised when running this program the result shown is 0, while what I expected was 2. Where am I wrong?

int main(int argc, char const *argv[]){
  int msec = 0;
  clock_t before = clock();
  sleep(2);
  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  printf("Time taken %d seconds\n",msec/1000);
}

Upvotes: 1

Views: 881

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222354

clock measures processor time used by your program. Your program does not use processor time while it is sleeping. The rest of your program uses less than a millisecond of time.

To measure “wall clock” or “real world” time, use time, and use difftime to subtract to time_t values, the type returned by time:

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

int main(int argc, const char *argv[])
{
    time_t before = time(NULL);
    sleep(2);
    double difference = difftime(time(NULL), before);
    printf("The time taken was %g seconds.\n", difference);
}

Upvotes: 6

Related Questions