Tiempo multiplataforma de alta precisión en 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?

preguntado el 10 de marzo de 12 a las 11:03

3 Respuestas

Since you are using Pygame, you should use pygame's function for abstracting that:

solo llama 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.

respondido 10 mar '12, 15:03

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.

respondido 10 mar '12, 11:03

Para obtener la mejor medida del tiempo transcurrido (desde Python 3.3), use time.perf_counter.

Devuelve el valor (en fracciones de segundo) de un contador de rendimiento, es decir, un reloj con la resolución más alta disponible para medir una duración corta. Incluye el tiempo transcurrido durante el sueño y abarca todo el sistema. El punto de referencia del valor devuelto no está definido, por lo que solo es válida la diferencia entre los resultados de llamadas consecutivas.

respondido 29 nov., 17:14

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.