Skip to content

Instantly share code, notes, and snippets.

@shenlebantongying
Created May 11, 2021 02:27
Show Gist options
  • Save shenlebantongying/6183ce66faede51f8b59aa1e6905b563 to your computer and use it in GitHub Desktop.
Save shenlebantongying/6183ce66faede51f8b59aa1e6905b563 to your computer and use it in GitHub Desktop.
Measure function run time with "with" statement
#!/usr/bin/env python3
import time
class Timer:
"""
A hack to measure function runtime with some hacking
https://preshing.com/20110924/timing-your-code-using-pythons-with-statement/
"""
def __enter__(self):
self.start = time.perf_counter() # this function used to be time.clock()
return self
def __exit__(self, *args):
self.end = time.perf_counter()
self.interval = self.end - self.start
def quartic_power():
res = 0
for i in range(0, 100):
for j in range(0, 100):
for k in range(0, 100):
for x in range(0, 100):
res += i * j * k * x
with Timer() as t:
quartic_power()
print(t.interval)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment