| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
import cProfile |
| 26 |
import pstats |
| 27 |
from datetime import datetime, timezone |
| 28 |
from pathlib import Path |
| 29 |
from typing import Callable, Tuple |
| 30 |
|
| 31 |
from .Shared import envVariableIsSet |
| 32 |
|
| 33 |
PROFILE_ENV_VAR = "TENSILE_PROFILE" |
| 34 |
|
| 35 |
|
| 36 |
def profile(func: Callable) -> Callable: |
| 37 |
"""Profiling decorator. |
| 38 |
|
| 39 |
Add ``@profile`` to mark a function for profiling; set the environment variable |
| 40 |
TENSILE_PROFILE=ON to enable profiling decorated functions. |
| 41 |
""" |
| 42 |
if not envVariableIsSet(PROFILE_ENV_VAR): |
| 43 |
return func |
| 44 |
|
| 45 |
def wrapper(*args, **kwargs): |
| 46 |
path, filename = initProfileArtifacts(func.__name__) |
| 47 |
|
| 48 |
prof = cProfile.Profile() |
| 49 |
output = prof.runcall(func, *args, **kwargs) |
| 50 |
result = pstats.Stats(prof) |
| 51 |
result.sort_stats(pstats.SortKey.TIME) |
| 52 |
result.dump_stats(path / filename) |
| 53 |
|
| 54 |
return output |
| 55 |
|
| 56 |
return wrapper |
| 57 |
|
| 58 |
|
| 59 |
def initProfileArtifacts(funcName: str) -> Tuple[Path, str]: |
| 60 |
"""Initializes filenames and paths for profiling artifacts based on the current datetime |
| 61 |
Args: |
| 62 |
funcName: The name of the function being profiled, nominally passed via func.__name__ |
| 63 |
Returns: |
| 64 |
A tuple (path, filename) where the path is the artifact directory and filename is |
| 65 |
a .prof file with the profiling results. |
| 66 |
""" |
| 67 |
dt = datetime.now(timezone.utc) |
| 68 |
filename = f"{funcName}-{dt.strftime('%Y-%m-%dT%H-%M-%SZ')}.prof" |
| 69 |
path = Path().cwd() / f"profiling-results-{dt.strftime('%Y-%m-%d')}" |
| 70 |
path.mkdir(exist_ok=True) |
| 71 |
return path, filename |