Skip to content

Instantly share code, notes, and snippets.

@the5fire
Created July 17, 2017 07:12
Show Gist options
  • Save the5fire/361d4bef6cbc5dc0b1b38e8fc94173e3 to your computer and use it in GitHub Desktop.
Save the5fire/361d4bef6cbc5dc0b1b38e8fc94173e3 to your computer and use it in GitHub Desktop.
# 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()
with TimeIt('+=') as ti:
lis = ''
for i in range(1000):
lis += '<li>%s</li>' % str(i)
result = '<ul>%s</ul>' % lis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment