Advertisement
Korotkodul

B3

Sep 21st, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. import time
  2.  
  3. from typing import Callable, TypeVar
  4.  
  5. T = TypeVar("T")
  6.  
  7. def is_floats_eq(lhs: float, rhs: float, eps: float = 1e-6) -> bool:
  8.     return abs(lhs - rhs) < eps
  9.  
  10.  
  11.  
  12. def collect_statistic(
  13.     statistics: dict[str, list[float, int]]
  14. ) -> Callable[[T], T]:
  15.     # ваш код
  16.     def recycle(func):
  17.         global statistics
  18.         start = time.time()
  19.         func()
  20.         end = time.time()
  21.         """
  22.        print("check")
  23.        print("statistics", statistics)
  24.        print("func", func.__name__)
  25.        print(statistics)
  26.        """
  27.         if func.__name__ not in statistics.keys():
  28.             #print("zero")
  29.             statistics[func.__name__] = [0.0, 0]
  30.         #print("check done")
  31.         n = statistics[func.__name__][1]
  32.         statistics[func.__name__][1] += 1
  33.         statistics[func.__name__][0] = (statistics[func.__name__][0] * n  +  end - start) / (n + 1)
  34.         return func
  35.     return recycle
  36.  
  37. statistics: list[str, list[float, int]] = {}
  38. #сверху или снизу?
  39.  
  40. @collect_statistic(statistics)
  41. def func1() -> None:
  42.     time.sleep(2)
  43.     #print(statistics)
  44.  
  45.  
  46. @collect_statistic(statistics)
  47. def func2() -> None:
  48.     time.sleep(1)
  49.     #print(statistics)
  50.  
  51. #print("func1")
  52. for i in range(3):
  53.     func1()
  54.  
  55. #print()
  56. #print("func2")
  57. for i in range(6):
  58.     func2()
  59.  
  60. eps = 1e-3
  61.  
  62. assert statistics[func1.__name__][1] == 3
  63. assert statistics[func2.__name__][1] == 6
  64. assert is_floats_eq(statistics[func1.__name__][0], 2, eps)
  65. assert is_floats_eq(statistics[func2.__name__][0], 1, eps)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement