Skip to content

Instantly share code, notes, and snippets.

@nepsilon
Last active July 6, 2016 01:24
Show Gist options
  • Save nepsilon/8a27fb3c117f347223f954c288eb4050 to your computer and use it in GitHub Desktop.
Save nepsilon/8a27fb3c117f347223f954c288eb4050 to your computer and use it in GitHub Desktop.
A simple way to benchmark your code in Python — First published in fullweb.io issue #50

A simple way to benchmark your code in Python

You’re working on your script and want to see how fast a function would be. Here’s how to do that with the timeit module, included in the standard library.

Let’s say you have the following script:

import random

def sort_rand():
  random.seed('pouet')
  pool = [random.random() for i in range(1000)]
  sorted_pool = sorted(pool)
  return sorted_pool

if __name__ == "__main__":
  sorted_nb = sort_rand() 

And you want to check how fast sort_rand() could be. Just add these 3 lines:

import random

def sort_rand():
  random.seed('pouet')
  pool = [random.random() for i in range(1000)]
  sorted_pool = sorted(pool)
  return sorted_pool

if __name__ == "__main__":
  sorted_nb = sort_rand()

  from timeit import Timer
  print(Timer("sort_rand()", setup="from __main__ import sort_rand")
              .repeat(repeat=3, number=1000))

This will print the time, in seconds, to run sort_rand() 1000 times, and repeat that 3 times. The default number of calls if not provided is 1,000,000.

The output is a simple Python list with the elapsed time as a float, so you can call min(), max() and the likes to get the number the most meaningful to you. Be sure to see the official doc for more info and examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment