Skip to content

Commit

Permalink
Merge pull request #48 from aparamon/optional-print
Browse files Browse the repository at this point in the history
Add parameter to disable `print(...)`
  • Loading branch information
illagrenan committed Sep 11, 2018
2 parents 3235811 + d3a966c commit 0990270
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
19 changes: 16 additions & 3 deletions block_timer/timer.py
@@ -1,8 +1,10 @@
# -*- encoding: utf-8 -*-
# ! python3

import sys
import time
from contextlib import ContextDecorator
from typing import Optional

__all__ = ["Timer"]

Expand Down Expand Up @@ -31,8 +33,17 @@ class Timer(ContextDecorator):
>>> print(t.elapsed)
"""

def __init__(self, title: str = ""):
def __init__(self, title: str = "", print_title: Optional[bool] = True, print_file=sys.stderr):
"""
Instantiate new Timer.
:param title: Title (prefix) that will be printed
:param print_title: Should print elapsed time?
:param print_file: File that will be passed to print function, see: https://docs.python.org/3/library/functions.html#print
"""
self._title = title
self._print_title = print_title
self._print_file = print_file
self._elapsed = 0

def __float__(self) -> float:
Expand All @@ -57,9 +68,11 @@ def __enter__(self) -> 'Timer':

def __exit__(self, *args):
self._elapsed = time.perf_counter() - self.start
title = "[{}] ".format(self._title) if self._title else ""

print('{title}Total time {total_seconds:.5f} seconds.'.format(title=title, total_seconds=self._elapsed))
if self._print_title:
title = "[{}] ".format(self._title) if self._title else ""
formatted_title = '{title}Total time {total_seconds:.5f} seconds.'.format(title=title, total_seconds=self._elapsed)
print(formatted_title, file=self._print_file)

@property
def elapsed(self) -> float:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -7,7 +7,7 @@

setup(
name='block-timer',
version='0.1.2',
version='0.2.0',
description="""Measure execution time of your code blocks""",
long_description=io.open("README.rst", 'r', encoding="utf-8").read(),
url='https://github.com/illagrenan/block-timer',
Expand Down
8 changes: 4 additions & 4 deletions tests/test_timer.py
Expand Up @@ -47,16 +47,16 @@ def test_multiple_instances(self):
self.assertIsNot(t1, t2)

def test_stdout(self):
with io.StringIO() as buffer1, redirect_stdout(buffer1):
with Timer(title="Some title"):
with io.StringIO() as buffer1:
with Timer(title="Some title", print_file=buffer1):
time.sleep(1 / 5)

output1 = buffer1.getvalue()

self.assertRegex(output1, re.compile(r"\[Some title\] Total time \d+\.\d+ seconds.\n", re.UNICODE))

with io.StringIO() as buffer2, redirect_stdout(buffer2):
with Timer(title="Different title"):
with io.StringIO() as buffer2:
with Timer(title="Different title", print_file=buffer2):
time.sleep(1 / 5)

output2 = buffer2.getvalue()
Expand Down

0 comments on commit 0990270

Please sign in to comment.