Created
April 10, 2021 14:30
-
-
Save dominik-ba/ce23e4c1edd0a5e009c412e86533f6a6 to your computer and use it in GitHub Desktop.
python performance measurement
This file contains 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
import time | |
def measure(method, verbose=True, *params): | |
start = time.perf_counter() | |
result = method(*params) | |
for i in range(100000): | |
i + 1 | |
end = time.perf_counter() | |
duration = end - start | |
if verbose: | |
print("Tested Method: {}".format(method.__name__)) | |
print("Param: <{}>".format(*params)) | |
print("Return value: <{}>".format(result)) | |
print("Time it took: {}".format(duration)) | |
print() | |
return duration | |
def simple_example(): | |
# Simple measurement | |
import math | |
measure(math.sqrt, 42, verbose=True) | |
def complex_example(): | |
# A bit more complex usage for comparison | |
verbose = False | |
iterations = 100 | |
method_1 = 0 | |
method_2 = 0 | |
for i in range(iterations): | |
value = "parameter1 for testing" | |
a = measure(method1,verbose, value) | |
b = measure(method2,verbose, value) | |
if a < b: | |
method_1+=1 | |
else: | |
method_2+=1 | |
value = "parameter 2 for testing" | |
a = measure(method1,verbose, value) | |
b = measure(method2,verbose, value) | |
if a < b: | |
method_1+=1 | |
else: | |
method_2+=1 | |
print("Method 1 was faster this many times: {}".format(method_1)) | |
print("Method 2 was faster this many times: {}".format(method_2)) | |
if __name__ == "__main__": | |
simple_example() | |
complex_example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment