-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtiming.py
More file actions
36 lines (29 loc) · 1.08 KB
/
timing.py
File metadata and controls
36 lines (29 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# timing.py
#
# You can execute this module typing for example: python timing.py "[x**2 for x in range(100_000)]" -r 15
print('loading timing...')
"""
Times how long a snippet of code takes to run
over multiple iterations
"""
from time import perf_counter
from collections import namedtuple
import argparse
Timing = namedtuple('Timing', 'repeats elapsed average')
def timeit(code, repeats=10):
code = compile(code, filename='<string>', mode='exec')
start = perf_counter()
for _ in range(repeats):
exec(code)
end = perf_counter()
elapsed = end -start
average = elapsed / repeats
return Timing(repeats, elapsed, average)
if __name__ == '__main__':
# get code, repeats from arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('code', type=str, help='The Python code snippet to time.')
parser.add_argument('-r', '--repeats', type=int, default=10, help='Number of times to repeat the test.')
args = parser.parse_args()
print(f'timing: {args.code}...')
print(timeit(code=str(args.code), repeats=args.repeats))