I'm making a blocking algorithm, and I just realised that adding a timeout to such algorithm is not so easy if it should remain precise.
Adding timeout means, that the blocking algorithm should abort after X ms if not earlier. Now I seem to have two options:
- Iterating time (has mistake, but is fast)
- Check blocking condition
- Iterate
time_elapsed
by 1 (which means 1e-6 sec with use of usleep) - Compare
time_elapsed
withtimeout
. (here is the problem I will talk about) usleep(1)
- Getting system time every iteration (slow, but precise)
- I know how to do this, please do not post any answers about that.
Compating timeout
with time_elapsed
And here is what bothers me. The timeout
will be in milliseconds (10e-3) while usleep
sleeps for 10e-6 seconds. So my time_elapsed
will be 1000 times more precise than timeout
. I want to truncate last three digits of time_elapsed
(operation equal to floor($time_elapsed/1000)
without dividing it. Division algorithm is too slow.
Summary
I want to make my variable 1000 times smaller without dividing it by 1000. I want just get rid of the data. In binary I'd use bit-shift operator, but have no idea how to apply it on decimal system.
Code sample:
Sometimes, when people on SO cannot answer the theoretical question, they really hunger for the code. Here it is:
floor($time_elapsed/1000);
I want to replace this code with something much faster. Please note that though the question itself is full of timeouts, the question title is only about truncating that data. Other users may find the solution useful for other purposes than timing.