开发者

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/ref开发者_如何转开发erence/clibrary/ctime/clock/

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


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.


Use boost::this_thread::sleep

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜