Created
June 27, 2018 17:16
-
-
Save karthikeyann/e67b9c9b6175dcc434e1e0dd19bd241a to your computer and use it in GitHub Desktop.
Measures Time taken and Memory before and after for a block of Python 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
import time | |
import os | |
import psutil | |
class MeasureMemTime: | |
def __init__(self): | |
self.start = None | |
self.end = None | |
self.startmem = None | |
self.endmem = None | |
def __enter__(self): | |
self.start = time.time() | |
self.startmem = psutil.Process(os.getpid()).get_memory_info().rss | |
print("Memory before start (Bytes): ", self.startmem) | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.end = time.time() | |
self.endmem = psutil.Process(os.getpid()).get_memory_info().rss | |
print("Total time taken (ms): ", self.duration()) | |
print("Memory after finish (Bytes): ", self.endmem) | |
def duration(self): | |
return str((self.end - self.start) * 1000) + ' milliseconds' | |
import time | |
def foo(): | |
time.sleep(1) | |
with MeasureMemTime() as m: | |
foo() # We can place here the multiple calls or arbitary code block to measure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment