Last active
August 19, 2018 03:37
-
-
Save et4891/f46ecf348d8e4cbd391d4b7681633368 to your computer and use it in GitHub Desktop.
Python comes with a timeit module specifically designed for benchmarking snippets of code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# just an example of how the `timeit` works | |
# below is an example of class attribute vs method parameter performance | |
class CircleTime(): | |
def __init__(self, radius=1): | |
self.pi = 3.14 | |
self.radius = 1 | |
# use class attribute pi | |
def get_circum_self(self): | |
return self.pi * self.radius * 2 | |
# use param for pi | |
def get_circum_pi(self, pi, radius): | |
return pi * radius * 2 | |
# run the method directly | |
print(timeit.timeit('CircleTime().get_circum_self()', setup='from __main__ import CircleTime', number=10000)) | |
# passing parameters | |
print(timeit.timeit('CircleTime().get_circum_pi(111,1)', setup='from __main__ import CircleTime', number=10000)) | |
# passing parameters with variables | |
num_pi = 3.14 | |
num_radius = 1 | |
print(timeit.timeit( | |
stmt='CircleTime().get_circum_pi(num_pi,num_radius)', # method | |
setup='from __main__ import CircleTime', # import the class | |
number=10000, # how many loops to run | |
globals={ # passing variables | |
'num_pi': num_pi, | |
'num_radius': num_radius | |
}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment