python - 如何使用 Raspberry Pi 获得更精确的时间测量?

标签 python performance time raspberry-pi raspbian

最近在开发一个基于raspberrypi 2b+的设备,连接mpu9250(自己焊接)。

我可以正确读取 9 轴数据,但我注意到每个数据输入都有不同的时间差:

图中显示了每两个数据之间的时间差。 但是我已经使用 QTimer 来确保我的代码每 10ms 读取 mpu9250 一次。

所以我在 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()

结果:

enter image description here

即使是这些简单的代码仍然在图表上显示峰值,这让我很失望......

谁能帮我解决这些问题或解释一下这是怎么回事?

最佳答案

在您的第一个测试中,您使用的是 QTimer,它将计时器视为后台任务。 QT 主要专注于提供响应式 GUI。

在您的第二个测试中,您在循环中有一个打印语句——打印中涉及的许多因素都可能导致执行该语句所需的时间发生变化。

看看 threading.Timer类以获得更好的方法。

文档说:

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method.

请注意,它还说:

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

换句话说,它不会是完美的,但很可能比您现在看到的要好得多。


如果您对更高精度的测量时间感兴趣,而不是更高精度地安排任务,请考虑使用 time.perf_counter()在 Python 3 中可用。

关于python - 如何使用 Raspberry Pi 获得更精确的时间测量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39891809/

相关文章:

python - 使用 lxml 动态创建 xml

java - 图片加载时间过长?

time - 在 Rails 3 中使用 distance_of_time_in_words

r - 扩展为1分钟,计算平均值

c - 简单的 c 程序不产生所需的输出

python - 如何将 dict 转换为递归 defaultdict 并加载 JSON?

python - 如何在 Wampserver 上设置和运行 Python?

python - worker 寻址策略

r - 为什么来自mgcv的bam对于某些数据比较慢?

java - 优化频繁flush()