DeadCapacitor
DeadCapacitor

Reputation: 209

Why am I getting excessive CPU Usage with "clock( )"?

I'm trying to create a simple timer using the clock() method. When the application is executed, my CPU usage jumps from 0% to 25%. For a simple program that does nothing but count from 60 to 0 in seconds, it's a bit excessive.

I was following this: http://www.cplusplus.com/reference/clibrary/ctime/clock/

Any reason for this? Are there any alternatives I could use?

Upvotes: 1

Views: 287

Answers (4)

sarnold
sarnold

Reputation: 104050

Most simple timing tests are better run with some pseudo-code like this:

start = get_time()
for 1 .. 10:
    do_the_task()
end = get_time()
diff = end - start
print "%d seconds elapsed", diff

On Unix-derived platforms, gettimeofday(2) returns a struct with seconds and microseconds since the Epoch, which makes for some pretty decent resolution timing. On other platforms, you'll have to hunt around for decent time sources.

Upvotes: 0

Keith
Keith

Reputation: 6834

See:

http://msdn.microsoft.com/en-us/library/ms686298%28v=vs.85%29.aspx

The code you reference:

 while (clock() < endwait) {}

will clearly just chew CPU while waiting for the time to pass, hence the 25% usage ( one core).

while (clock() < endwait) { Sleep(1);}

should solve your problem.

Upvotes: 3

peoro
peoro

Reputation: 26060

My best guess is that your problem is not the clock function, but the wait function.

It loops until a certain time is reached. You should use a function that actually suspends your program, like the sleep function.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Use boost::this_thread::sleep

// sleep for one second
boost::this_thread::sleep(boost::posix_time::seconds(1));

Upvotes: 2

Related Questions