How to get more accurate measures of time with raspberries?

Recently, I am developing a device base on raspberrypi 2b + that connects to mpu9250 (welding itself).

I could read 9-axis data correctly, but noticed that each data input with a different time differential:

the figure shows the time difference between each two data. But I used QTimer to make sure my code reads mpu9250 once every 10 ms.

So, I tried this code on RaspberryPi 2b +:

import time import matplotlib.pyplot as plt time_arr = [] for i in range(5000): t0 = time.time() print "K" t1 = time.time() - t0 time_arr.append(t1) plt.plot(time_arr) plt.show() 

And the result:

enter image description here

even this simple code still shows peaks in the diagram, and it knocked me down ...

Can someone help me solve this problem or explain what is happening?

+5
source share
1 answer

In your first test, you use QTimer, which treats a timer as a background task. QT is primarily focused on providing a flexible graphical interface.

In your second test, you have a print statement in a loop - there are a number of factors in the print that can cause a change in the time required to execute the instruction.

Take a look at the threading.Timer class for a better approach.

The documentation says:

This class represents an action that should only be started after a certain amount of time has passed - a timer. Timer is a subclass of Thread and by itself also serves as an example of creating custom threads.

Timers are started, like threads, by calling the start () method. The timer can be stopped (before it starts) by calling the cancel () method.

Note that he also says:

The interval that the timer will wait before its action may not be the same as the interval specified by the user.

In other words, it will not be perfect, but it will most likely be significantly better than what you see now.


If you are interested in MEASUREMENT time with higher accuracy, and not in planning tasks with better accuracy, consider using time.perf_counter() , which is available in Python 3.

+1
source

Source: https://habr.com/ru/post/1257782/


All Articles