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.2 Django 4.2 Django 3.2 Python 3

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.