Millisecond precise python timer

python, timer

Solution

IMHO the problem is not in your script but more probably in your machine. I assume you are using a standard computer under Linux or Windows. And even if the computer is able to do many things in one single milliseconds, it constantly does with :

- network

- mouse or keyboard events

- screen (including screen savers ...)

- antivirus software (mainly on Windows)

- system or daemon processes (and there are plenty of them)

- multi-task management

You cannot reliably hope to have a one millisecond accuracy without a dedicated hardware equipement or you must use a real time system.

Edit:

As a complement, here is a quote from an answer from Ulrich Eckhardt to this other post Inconsistent Python Performance on Windows :

You have code that performs serial IO, which will block your process and possibly invoke the scheduler. If that happens, it will first give control to a different process and only when that one yield or exceeds its timeslice it will re-schedule your process.

The question for you is: What is the size of the scheduler timeslice of the systems you are running? I believe that this will give you an insight into what is happening.

Problem

I work on a python script designed to control multiple actuator at the same time. To simplify, let's say I need to control 2 electric motors. With the multiprocessing module I create a process for each motors, and a process to save the data on a sheet. This part of the script works fine, however I need to command my motors at precise times, every milliseconds, and the time.time() or the time.clock() functions seems to be unreliable (triggs between 0.05 and 30 millisecond!) Is it "normal" for these functions to be so erratic, or is this caused by another part of my script? EDIT: I used the datetime function (see below) to improve the precision, but I still have several discrete level of error. For example, if I want 1ms, I get also 1.25, 0.75,1.5... So IMO this is due to computer hardware(as Serge Ballesta said).

Original source