From 1e19ecbb31927ba82dcb415124ed1ec460ecb145 Mon Sep 17 00:00:00 2001
From: Pierre-Antoine Rouby <pierre-antoine.rouby@inrae.fr>
Date: Tue, 18 Apr 2023 12:04:20 +0200
Subject: [PATCH] tools: Add timer function wrapped.

---
 src/pamhyr.py | 10 +++++++++-
 src/tools.py  | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 61 insertions(+), 2 deletions(-)

diff --git a/src/pamhyr.py b/src/pamhyr.py
index b56d0af9..5a8b2b71 100755
--- a/src/pamhyr.py
+++ b/src/pamhyr.py
@@ -8,10 +8,15 @@ from PyQt5.QtCore import QTranslator
 from PyQt5.QtWidgets import QApplication
 
 from config import Config
+from tools import (
+    reset_timers, display_timers, timer
+)
+
 from View.MainWindow import ApplicationWindow
 from Model.Study import Study
 
 def main():
+    reset_timers()
     conf = Config.load()
     app = QApplication(sys.argv)
 
@@ -39,7 +44,10 @@ def main():
 
     application = ApplicationWindow(conf=conf)
     application.show()
-    sys.exit(app.exec_())
+
+    ret = app.exec_()
+    display_timers()
+    sys.exit(ret)
 
 if __name__ == "__main__":
     main()
diff --git a/src/tools.py b/src/tools.py
index 34805ed4..ad559a45 100644
--- a/src/tools.py
+++ b/src/tools.py
@@ -1,9 +1,60 @@
 # -*- coding: utf-8 -*-
 
+import time
 from functools import (
-    reduce, partial
+    reduce, partial, wraps
 )
 
+##########
+# TIMERS #
+##########
+
+_timers = {}
+_calls = {}
+
+def reset_timers():
+    global _timers
+    global _calls
+
+    _timers = {}
+    _calls = {}
+
+def display_timers():
+    global _timers
+    global _calls
+
+    print(" +--Timers----------------------------------------+")
+    for func in _timers:
+        print(f" | {func:<15} | {_timers[func]:>10.6f} sec | {_calls[func]:>5} calls |")
+    print(" +------------------------------------------------+")
+
+def timer(func):
+    """Function wrapper to register function runtime"""
+    @wraps(func)
+    def wrapper(*args, **kwargs):
+        start_time = time.perf_counter()
+
+        value = func(*args, **kwargs)
+
+        end_time = time.perf_counter()
+        run_time = end_time - start_time
+
+        if func.__name__ not in _timers:
+            _timers[func.__name__] = 0
+            _calls[func.__name__] = 0
+
+        _timers[func.__name__] += run_time
+        _calls[func.__name__] += 1
+
+        return value
+
+    return wrapper
+
+################
+# OTHERS TOOLS #
+################
+
+@timer
 def flatten(lst):
     """Flatten list of list
 
-- 
GitLab