Reputation: 2695
I'm writing a game that should run on several platforms. I need a good time accuracy on all platforms.
I am not interested in knowing the time of the day, what matters to me is the elapsed time between two calls.
After reading the docs, time.time appears better on Linux and time.clock better on Windows. I thought of writing something like this:
import os
import time
__all__ = ['hrtime']
platform = os.name
if platform == 'posix':
hrtime = time.time
elif platform == 'nt':
hrtime = time.clock
else:
# 'os2', 'ce', 'java', 'riscos'
raise ValueError("I have no idea what I'm doing.")
But what about the other platforms? Does MacOS return {posix}? What about cygwin, is that a Linux or a Windows? What is 'ce'? Should I even care about these platforms at all?
Another option could be to use the SDL time from pygame. This seems to have a millisecond accuracy on every platform. Since I'm using SDL for the rendering I don't mind using that. However, I am working on network code now, and using the SDL time in my network code feels a bit strange.
Question: what would you rather use, and why?
Upvotes: 3
Views: 705
Reputation: 38749
For the best measure of elapsed time (since Python 3.3), use time.perf_counter
.
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
Upvotes: 1
Reputation: 110156
Since you are using Pygame, you should use pygame's function for abstracting that:
just call pygame.time.get_ticks()
- it will return the microseconds since the call to pygame.init()
It is not that unusual to have programs other than multimedia oriented programs to call SDL functions from pygame for things like sound warnings or even keyboard reading - there should be no problem using that.
Upvotes: 1
Reputation: 117641
I have always used this and never ran into any problems:
import sys
import time
if sys.platform == "win32":
# on Windows, the best timer is time.clock()
timerfunc = time.clock
else:
# on most other platforms, the best timer is time.time()
timerfunc = time.time
And even if you'd run into some problems on some other platform, it's always easy to adapt the code later.
I would suggest against using SDL for this, for the reason you mentioned, as well as that the increase in precision (if any) probably is not even noticeable.
Upvotes: 1