I was wondering what the difference/s was/were between time.sleep(5)
and the following piece of code:
import time
start_time = time.time()
while True:
if time.time() - start_time > 5:
break
print("Five seconds passed")
And also, is it better to use the first or the second solution?
Probably, using the while
loop like I did, is not a good solution.
Thanks in advice.
The while True
loop is called a Busy Wait [Wikipedia], because it will keep the processor running. This will probably keep 1 core at 100%.
A time.sleep()
is an Idle Wait, because the processor has nothing to do. Your CPU will be at 0% if not used by something else.
And now, things will become difficult, if you want to fully understand it and it probably depends on the operating system.
thread scheduling in Windows happens at 1/64s, if not changed. Whatever your program does, it probably has a precision of 1/64s, because that's the interval when Windows will wake the thread up.
keeping the CPU busy will keep the thread priority same or even lower it.
keeping the CPU busy will make it warm. CPUs don't like heat and they may actually slow down or at least stop TurboBoost (or similar CPU feature)
keeping the CPU idle will increase the thread priority. It will use a synchronization object and call WaitForSingleObject() [MSDN] thus giving the CPU back to the operating system.
What will actually happen or which method is more precise is very hard to predict. To fully understand what happens on Windows, read the Windows Internals book [Amazon] part 1 about processes and threads.