Debian Codegraph @

tensilelite/Tensile/Utilities/Decorators/Profile.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2016-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
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