utils.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import typing
  2. from contextlib import contextmanager
  3. import time
  4. from synergine2.base import BaseObject
  5. class ChunkManager(BaseObject):
  6. def __init__(self, chunks_numbers: int):
  7. self._chunks_numbers = chunks_numbers
  8. def make_chunks(self, data: list) -> list:
  9. if self._chunks_numbers == 1:
  10. return [data]
  11. i, j, x = len(data), 0, []
  12. for k in range(self._chunks_numbers):
  13. a, j = j, j + (i + k) // self._chunks_numbers
  14. x.append(data[a:j])
  15. return x
  16. def get_mechanisms_classes(mechanized) -> ['Mechanisms']:
  17. mechanisms_classes = []
  18. for behaviour_class in mechanized.behaviours_classes:
  19. mechanisms_classes.extend(behaviour_class.use)
  20. return list(set(mechanisms_classes)) # Remove duplicates
  21. class ElapsedTime(object):
  22. def __init__(self, start_time: float) -> None:
  23. self.start_time = start_time
  24. self.end_time = None
  25. def get_final_time(self) -> float:
  26. assert self.end_time
  27. return self.end_time - self.start_time
  28. def get_time(self) -> float:
  29. return time.time() - self.start_time
  30. @contextmanager
  31. def time_it() -> typing.Generator[ElapsedTime, None, None]:
  32. elapsed_time = ElapsedTime(time.time())
  33. try:
  34. yield elapsed_time
  35. finally:
  36. elapsed_time.end_time = time.time()