Created
July 17, 2017 07:56
-
-
Save the5fire/1ba309c7c6b256b87eecb8baaaf97398 to your computer and use it in GitHub Desktop.
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
# coding:utf-8 | |
from __future__ import print_function | |
import gc | |
import os | |
import psutil | |
import sys | |
import time | |
class TimeIt(object): | |
def __init__(self, scope_name="", fd=sys.stdout): | |
self._start = None | |
self._fd = fd | |
self._fmt = 'block took {{secs:.5f}} seconds to run [{}]'.format(scope_name) | |
def __enter__(self): | |
# run the garbage collector | |
# then disable it so it won't tamper with the measurments | |
gc.collect() | |
gc.disable() | |
self._start = time.time() | |
self._befor_rss = psutil.Process(os.getpid()).memory_info().rss | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
now = time.time() - self._start | |
print(self._fmt.format(secs=now).strip(), file=self._fd) | |
print((psutil.Process(os.getpid()).memory_info().rss - self._befor_rss) / 1024.0) | |
# from guppy import hpy | |
# h = hpy() | |
# print(h.heap()) | |
# enable garbage collection after we're done with measurments | |
gc.enable() | |
class Foo(object): | |
result = '' | |
f = Foo() | |
with TimeIt('+=') as ti: | |
for i in range(1000): | |
f.result += '<li>%s</li>' % str(i) | |
result = '<ul>%s</ul>' % f.result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment