About Quickly Measuring a Method Execution Time in Django Shell

You can use timeit module to quickly measure a method execution time in Django shell, as follows:

>>> from timeit import timeit
>>> from posts.models import Post
>>> p = Post.objects.first()
>>> timeit(lambda: p.generate_pdf(), number=5)
5.923993167001754
>>> timeit(lambda: p.generate_docx(), number=5)
2.7514753749710508

The number argument tells the timeit module to execute the callable 5 times and then calculates the average execution time.

Tips and Tricks Programming Optimization Performance Django 5.x Django 4.2 Django 3.2 Python 3