forked from huangsam/ultimate-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark.py
51 lines (37 loc) · 1.41 KB
/
benchmark.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import cProfile
import pstats
import time
# Module-level constants
_SLEEP_DURATION = .001
def finish_slower():
"""Finish slower."""
for _ in range(20):
time.sleep(_SLEEP_DURATION)
def finish_faster():
"""Finish faster."""
for _ in range(10):
time.sleep(_SLEEP_DURATION)
def main():
# Create a profile instance
profile = cProfile.Profile()
profile.enable()
for _ in range(2):
finish_slower()
finish_faster()
profile.disable()
# Sort statistics by cumulative time spent for each function call.
# There are other ways to sort the stats by, but this is the most
# common way of doing so. For more info, please consult Python docs:
# https://docs.python.org/3/library/profile.html
ps = pstats.Stats(profile).sort_stats("cumulative")
# Notice how many times each function was called. In this case, the main
# bottleneck for `finish_slower` and `finish_faster` is `time.sleep`
# which occurred 60 times. By reading the code and the statistics, we
# can infer that 40 occurrences came from `finish_slower` and 20 came
# from `finish_faster`. It is clear why the latter function runs faster
# in this case, but identifying insights like this are not simple in
# large projects. Consider profiling in isolation when analyzing complex
# classes and functions
ps.print_stats()
if __name__ == "__main__":
main()