Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a simple util function #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/hello_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import datetime
from typing import List, Optional

import src.utils


@dataclasses.dataclass
class Person:
Expand All @@ -19,6 +21,7 @@ def find_age(
return result[0].age


@src.utils.timer(lambda t: print("Function add takes " + str(t) + "ns"))
def add(a: int, b: int) -> int:
return a + b

Expand Down
22 changes: 22 additions & 0 deletions src/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import time
from typing import Any, Callable, TypeVar

RT = TypeVar("RT") # return type


def timer(
output_time_func: Callable[[int], None],
) -> Callable[[Callable[..., RT]], Callable[..., RT]]:
"""Decorator to measure performance"""

def decorator(func: Callable[..., RT]) -> Callable[..., RT]:
def wrapper(*args: Any, **kwargs: Any) -> RT:
t1 = time.perf_counter_ns()
result = func(*args, **kwargs)
t2 = time.perf_counter_ns()
output_time_func(t2 - t1)
return result

return wrapper

return decorator
31 changes: 31 additions & 0 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import time
import unittest
from typing import List

import src.utils


class TestBasic(unittest.TestCase):
def test_timer_records_correct_time(self) -> None:
@src.utils.timer(lambda t: self.assertGreater(t, 1e9))
def wait_one_sec() -> None:
time.sleep(1)

self.assertIsNone(wait_one_sec())

def test_timer_decorator_returns_correct_output(self) -> None:
@src.utils.timer(lambda _: None)
def return_int() -> int:
return 13

@src.utils.timer(lambda _: None)
def return_str() -> str:
return "hello world"

@src.utils.timer(lambda _: None)
def return_list() -> List[int]:
return [1, 2, 3]

self.assertEqual(return_int(), 13)
self.assertEqual(return_str(), "hello world")
self.assertListEqual(return_list(), [1, 2, 3])