Dramatic slowdown with random.random on free-threading build.
未关闭
还没有人认领这个 Issue。
performance
topic-free-threading
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
This slowdown was found with one of my favorite benchmarks, which is calculating the pi value with the Monte Carlo method.
import os
import random
import time
from threading import Thread
def monte_carlo_pi_part(n: int, idx: int, results: list[int]) -> None:
count = 0
for i in range(n):
x = random.random()
y = random.random()
if x*x + y*y <= 1:
count += 1
results[idx] = count
n = 10000
threads = []
num_threads = 100
results = [0] * num_threads
a = time.time()
for i in range(num_threads):
t = Thread(target=monte_carlo_pi_part, args=(n, i, results))
t.start()
threads.append(t)
while threads:
t = threads.pop()
t.join()
b = time.time()
print(sum(results) / (n * num_threads) * 4)
print(b-a)
Acquiring critical sections for random methods causes this slowdown.
Removing @critical_section from the method, which uses genrand_uint32 and then updating genrand_uint32 to use atomic operation makes the performance acceptable.
| Build | Elapsed | PI |
|---|---|---|
| Default (with specialization) | 0.16528010368347168 | 3.144508 |
| Free-threading (with no specialization) | 0.548654317855835 | 3.1421 |
| Free-threading with my patch (with no specialization) | 0.2606849670410156 | 3.141108 |
Linked PRs
- gh-118393
- gh-118396
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先阅读 random.random 的实现和 genrand_uint32 路径,包括 issue 中描述的 @critical_section 用法。然后复现提供的多线程 Monte Carlo 基准测试,再查看链接的 PR 118393 和 118396;当 free-threading 导致的性能下降得到缓解且不改变随机数的正确性时,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- performance
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100