Create decorators.py
Browse files- decorators.py +36 -0
decorators.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# decorators.py
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import torch
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
class spaces:
|
| 9 |
+
@staticmethod
|
| 10 |
+
def GPU(duration=0):
|
| 11 |
+
def decorator(func):
|
| 12 |
+
@functools.wraps(func)
|
| 13 |
+
def wrapper(*args, **kwargs):
|
| 14 |
+
if not torch.cuda.is_available():
|
| 15 |
+
raise RuntimeError("GPU no est谩 disponible.")
|
| 16 |
+
|
| 17 |
+
result = [None]
|
| 18 |
+
exception = [None]
|
| 19 |
+
|
| 20 |
+
def target():
|
| 21 |
+
try:
|
| 22 |
+
result[0] = func(*args, **kwargs)
|
| 23 |
+
except Exception as e:
|
| 24 |
+
exception[0] = e
|
| 25 |
+
|
| 26 |
+
thread = threading.Thread(target=target)
|
| 27 |
+
thread.start()
|
| 28 |
+
thread.join(duration)
|
| 29 |
+
|
| 30 |
+
if thread.is_alive():
|
| 31 |
+
raise TimeoutError(f"La ejecuci贸n de la funci贸n excedi贸 {duration} segundos.")
|
| 32 |
+
if exception[0]:
|
| 33 |
+
raise exception[0]
|
| 34 |
+
return result[0]
|
| 35 |
+
return wrapper
|
| 36 |
+
return decorator
|