Skip to content

Commit 114ce7f

Browse files
moto-metamthrok
andauthored
Add defaults for python_version and free_threaded fields (#1286)
Summary: These values can be determined at import time, so requiring users to manually specify them is cumbersome. The values are now computed once at module load and used as defaults for the dataclass fields. Differential Revision: D92268457 Co-authored-by: Moto Hira <moto@meta.com>
1 parent 443536f commit 114ce7f

File tree

1 file changed

+20
-27
lines changed

1 file changed

+20
-27
lines changed

examples/benchmark_utils.py

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,11 @@
4646
ProcessPoolExecutor,
4747
ThreadPoolExecutor,
4848
)
49-
from dataclasses import asdict, dataclass
49+
from dataclasses import asdict, dataclass, field
5050
from datetime import datetime, timezone
5151
from enum import Enum
5252
from functools import partial
53+
from sys import version_info
5354
from typing import Any, Generic, TypeVar
5455

5556
import numpy as np
@@ -60,6 +61,18 @@
6061
ConfigT = TypeVar("ConfigT")
6162

6263

64+
def _is_free_threaded() -> bool:
65+
"""Check if Python is running with free-threaded ABI."""
66+
try:
67+
return not sys._is_gil_enabled() # pyre-ignore[16]
68+
except AttributeError:
69+
return False
70+
71+
72+
_PYTHON_VERSION = f"{version_info.major}.{version_info.minor}.{version_info.micro}"
73+
_FREE_THREADED = _is_free_threaded()
74+
75+
6376
@dataclass
6477
class BenchmarkResult(Generic[ConfigT]):
6578
"""BenchmarkResult()
@@ -89,15 +102,15 @@ class BenchmarkResult(Generic[ConfigT]):
89102
date: str
90103
"""When benchmark was run. ISO 8601 format."""
91104

92-
python_version: str
105+
cpu_percent: float
106+
"""Average CPU utilization percentage during benchmark execution."""
107+
108+
python_version: str = field(default=_PYTHON_VERSION)
93109
"""Python version used for the benchmark"""
94110

95-
free_threaded: bool
111+
free_threaded: bool = field(default=_FREE_THREADED)
96112
"""Whether Python is running with free-threaded ABI."""
97113

98-
cpu_percent: float
99-
"""Average CPU utilization percentage during benchmark execution."""
100-
101114

102115
class ExecutorType(Enum):
103116
"""ExecutorType()
@@ -117,22 +130,6 @@ class ExecutorType(Enum):
117130
"""
118131

119132

120-
def _get_python_info() -> tuple[str, bool]:
121-
"""Get Python version and free-threaded ABI information.
122-
123-
Returns:
124-
Tuple of (``python_version``, ``is_free_threaded``)
125-
"""
126-
python_version = (
127-
f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
128-
)
129-
try:
130-
is_free_threaded = not sys._is_gil_enabled() # pyre-ignore[16]
131-
except AttributeError:
132-
is_free_threaded = False
133-
return python_version, is_free_threaded
134-
135-
136133
def _create_executor(executor_type: ExecutorType, max_workers: int) -> Executor:
137134
"""Create an executor of the specified type.
138135
@@ -324,7 +321,6 @@ def run(
324321

325322
cpu_mean = np.mean(cpu_samples)
326323

327-
python_version, free_threaded = _get_python_info()
328324
date = datetime.now(timezone.utc).isoformat()
329325

330326
result = BenchmarkResult(
@@ -334,8 +330,6 @@ def run(
334330
ci_lower=float(confidence_interval[0]),
335331
ci_upper=float(confidence_interval[1]),
336332
date=date,
337-
python_version=python_version,
338-
free_threaded=free_threaded,
339333
cpu_percent=float(cpu_mean),
340334
)
341335

@@ -347,9 +341,8 @@ def get_default_result_path(path: str, ext: str = ".csv") -> str:
347341
base, _ = os.path.splitext(os.path.realpath(path))
348342
dirname = os.path.join(os.path.dirname(base), "data")
349343
filename = os.path.basename(base)
350-
python_version, free_threaded = _get_python_info()
351344
version_suffix = (
352-
f"_{'.'.join(python_version.split('.')[:2])}{'t' if free_threaded else ''}"
345+
f"_{'.'.join(_PYTHON_VERSION.split('.')[:2])}{'t' if _FREE_THREADED else ''}"
353346
)
354347
return os.path.join(dirname, f"{filename}{version_suffix}{ext}")
355348

0 commit comments

Comments
 (0)