Coderzelf
Coderzelf

Reputation: 752

Incorrect Time in C++

I have the following code:

clock_t tt = clock();
sleep(10);
tt = clock()-tt;
cout<<(float)tt/CLOCKS_PER_SEC<<" "<<CLOCKS_PER_SEC<<endl;

When I run the code, it apparently pauses for 10 seconds and the output is:

0.001074 1000000

This indicates it passed 1074 clock ticks and 1ms, which is apparently false.

Why does this happen?

I am using g++ under linux.

Upvotes: 1

Views: 797

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36441

clock() doesn't measure elapsed time (what you would measure with a stopwatch), it measures the time spent by your program running on the CPU. But sleep() almost don't use any CPU, it simply makes your process going to sleep. Try to modify sleep(10) by any other value sleep(1)for example, and you will get the same result.

Upvotes: 2

Yamaguti
Yamaguti

Reputation: 156

The function clocks returns the processor time consumed by the program. While sleeping, your process does not use any amount of processing, so this is expected. The amount of time your program is showing could be from the clock function calling.

Upvotes: 4

Related Questions