Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform high-accuracy time in python

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?

like image 252
Niriel Avatar asked Dec 01 '25 06:12

Niriel


1 Answers

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.

like image 100
jsbueno Avatar answered Dec 03 '25 21:12

jsbueno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!