brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python3 -m timeit times a small piece of code for you

Python
~/tips/tip-python-timeit

python3 -m timeit "sum(range(1000))"

Runs a snippet many times and prints the best average time, so you can compare two ways to do something.

Two ways to write the same thing and you want to know which is faster. Do not use a stopwatch.

python3 -m timeit "sum(range(1000))"
python3 -m timeit -s "data = list(range(1000))" "sorted(data)"

-s holds setup code that is not timed. Python picks the number of loops itself and reports the best of several runs. Treat tiny differences as noise, and remember a snippet is not your whole program.

Further reading: timeit documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link