Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

unix - 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
",msec/1000);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
", difference);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...