View Single Post
Re: need your advice on clock()
Old
  (#6)
botmeister
Ex-Council Member
 
botmeister's Avatar
 
Status: Offline
Posts: 1,090
Join Date: Nov 2003
Location: Canada
Default Re: need your advice on clock() - 13-01-2004

Working with clock ticks is so much fun and so very confusing

I like what you've come up with, and you've got me revisting some of my existing "clock" code which probably can be made simpler and faster without losing any precision.

Anyhow, I looked over your code (and over) and found some minor things which are very subtle and may not matter much depending on the application, but there's one part which appears to be incorrect.

Here goes ...

static long current_clock;

The above line does not have to be static, however you may gain a performance edge by not allocating stack space for it on each call.

This line has a small error in it:

time_in_seconds = (float) current_clock / CLOCKS_PER_SEC;

After a rollover event, the elapsed time in seconds is actually:

time_in_seconds = (float) ( current_clock + 1 ) / CLOCKS_PER_SEC;

The extra clock tick is added because the rollover looks like this (assuming a MAX value of 2)

Code:
Clock ticks --->
0 1 2 0 1 2 0 1 2
	A B
The elapsed time from tick A to tick B is not 0 ticks, but 1 tick, however the exsisting calculation assumes 0 ticks elapsed, which is technically incorrect, but insignificant for timing the actions of a bot.

This line I cannot understand:

rollover_difference = (float) 286331153 / CLOCKS_PER_SEC * rollover_count;

What does 286331153 represent? If we are calculating the number of seconds elapsed during each rollover, then you should be using 2147483647 (2^31 - 1) as the constant (if I typed it in right). You should use the macro LONG_MAX to make the code machine independant.

(float) 286331153 / CLOCKS_PER_SEC is an inline division of two constants, you may as well precalculate this. The compiler may do this for you, but it would be cleaner to precalculate elsewhere.

You may want to replace the data type "float" with "double" because float does not have enough precision to get exact timing conversions in all cases.

The alternative function I posted reduces the number of divisions and multiplications which are computationally more expensive than addition and subtraction, it should reduce precision errors, and it should correct for all the errors I found (I hope anyway).

What I'd do next is replace float with double, and turn the function into a fully contained class object. There's probably still some performance improvements to be made in there as well.


Maker of the (mEAn) Bot.Admin Manager

"In theory, there is no difference between theory and practice. But, in practice, there is." - Jan L.A. van de Snepscheut

Last edited by botmeister; 13-01-2004 at 09:18..
  
Reply With Quote