You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python骰子模拟器性能优化请求:大数值掷骰与百分比运算提速

多骰子掷骰代码性能优化方案

核心优化点

  • 删除冗余的骰子生成逻辑:原代码连续两次生成完整的骰子结果列表,完全是重复操作,直接删掉其中一次就能减少一半的随机数生成开销。
  • 改用批量随机数生成:大数量掷骰场景下,用random.choices批量生成结果比循环调用randint再加列表append快得多——前者底层是C实现的批量操作,能大幅减少Python层面的循环开销。
  • 简化百分比计算:sum(num.values())的结果其实就是用户输入的dice_amount,直接用这个变量当总数,没必要额外求和;同时提前计算100 / dice_amount这个系数,避免在循环里重复做除法运算。
  • 可选:去掉不必要的排序:如果不需要按出现次数排序输出,直接遍历排序后的骰子面数(for face in sorted(num)),比most_common()的排序操作更高效,尤其当骰子面数较多时。

优化后的完整代码

import random
from collections import Counter

print("Hello and welcome to the dice roller!")
name = input("What is your name?: ")
print(f"Hi {name}")

while True:
    wants_to_play = input("Do you want to play? (y/n): ").lower()
    
    if wants_to_play == "y":
        dice_face = int(input("Select the number of faces you want your dice to have. WARNING: if you don't select a whole number, the dice roller won't work. "))
        dice_amount = int(input("Select how many dices of the given faces you want to roll: "))

        # 批量生成骰子结果,替代循环append
        dice_rolls = random.choices(range(1, dice_face + 1), k=dice_amount)
        
        # 统计各面出现次数
        num = Counter(dice_rolls)
        total = dice_amount
        # 提前计算百分比系数,避免循环内重复计算
        percent_factor = 100 / total

        print("Your dice percentages were: ")
        # 若无需按出现次数排序,可替换为 for face in sorted(num):
        for face, count in num.most_common():
            print(f"{face}: {count} ({count * percent_factor:.2f}%)")
      
    else:
        print("Well, it was great while it lasted! Until next time!")
        break

print("Developed by SMB Studios")

极致性能补充方案(针对超大量掷骰)

如果需要处理百万级别的掷骰请求,可改用numpy的批量随机数生成,性能会比标准库random提升一个量级:

import numpy as np
# 替换原骰子生成代码
dice_rolls = np.random.randint(1, dice_face + 1, size=dice_amount).tolist()

内容的提问来源于stack exchange,提问作者Samuel Molero Badia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:50:29