Measure how long something takes

Generally use time.monotonic() to get the current "uptime" of a board in fractional seconds. So to measure the duration it takes CircuitPython to do something:

import time
start_time = time.monotonic()
# put thing you want to measure here, like:
import neopixel
stop_time = time.monotonic()
print("elapsed time = ", stop_time - start_time)

Note that on the "small" versions of CircuitPython in the QT Py M0, Trinket M0, etc., the floating point value of seconds will become less accurate as uptime increases.

More accurate timing with ticks_ms(), like Arduino millis()

If you want something more like Arduino's millis() function, the supervisor.ticks_ms() function returns an integer, not a floating point value. It is more useful for sub-second timing tasks and you can still convert it to floating-point seconds for human consumption.

import supervisor
start_msecs = supervisor.ticks_ms()
import neopixel
stop_msecs = supervisor.ticks_ms()
print("elapsed time = ", (stop_msecs - start_msecs)/1000)

This guide was first published on Apr 02, 2022. It was last updated on Apr 02, 2022.

This page (Timing) was last updated on Apr 05, 2022.

Text editor powered by tinymce.