The testing suite doesn't make an attempt at using the imported timeit
so it's hard to tell what the intent was. Nonetheless, this is a canonical answer so a complete example of timeit
seems in order, elaborating on Martijn's answer.
The docs for timeit
offer many examples and flags worth checking out. The basic usage on the command line is:
$ python -mtimeit "all(True for _ in range(1000))"
2000 loops, best of 5: 161 usec per loop
$ python -mtimeit "all([True for _ in range(1000)])"
2000 loops, best of 5: 116 usec per loop
Run with -h
to see all options. Python MOTW has a great section on timeit
that shows how to run modules via import and multiline code strings from the command line.
In script form, I typically use it like this:
import argparse
import copy
import dis
import inspect
import random
import sys
import timeit
def test_slice(L):
L[:]
def test_copy(L):
L.copy()
def test_deepcopy(L):
copy.deepcopy(L)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=10 ** 5)
parser.add_argument("--trials", type=int, default=100)
parser.add_argument("--dis", action="store_true")
args = parser.parse_args()
n = args.n
trials = args.trials
namespace = dict(L = random.sample(range(n), k=n))
funcs_to_test = [x for x in locals().values()
if callable(x) and x.__module__ == __name__]
print(f"{'-' * 30}\nn = {n}, {trials} trials\n{'-' * 30}\n")
for func in funcs_to_test:
fname = func.__name__
fargs = ", ".join(inspect.signature(func).parameters)
stmt = f"{fname}({fargs})"
setup = f"from __main__ import {fname}"
time = timeit.timeit(stmt, setup, number=trials, globals=namespace)
print(inspect.getsource(globals().get(fname)))
if args.dis:
dis.dis(globals().get(fname))
print(f"time (s) => {time}\n{'-' * 30}\n")
You can pretty easily drop in the functions and arguments you need. Use caution when using impure functions and take care of state.
Sample output:
$ python benchmark.py --n 10000
------------------------------
n = 10000, 100 trials
------------------------------
def test_slice(L):
L[:]
time (s) => 0.015502399999999972
------------------------------
def test_copy(L):
L.copy()
time (s) => 0.01651419999999998
------------------------------
def test_deepcopy(L):
copy.deepcopy(L)
time (s) => 2.136012
------------------------------