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

如何在Python现有脚本中添加类秒表功能统计运行时长?

解决方案:为随机字符串生成器添加运行时长统计

直接在主脚本里用time库就能实现时长统计,不用单独写函数。同时帮你优化了原代码里生成字符串的冗余逻辑,以及提升了已尝试字符串的检查效率,具体修改如下:

修改后的完整代码

from string import ascii_lowercase
from random import choice
import time

# 记录程序开始时间
start_time = time.time()

attempts = 0
alphabet = list(ascii_lowercase)
# 用集合存储已尝试字符串,检查存在性的效率比列表高很多
failed_words = set()

while True:
    # 简化5位随机小写字母生成逻辑,避免多次replace操作
    current_word = ''.join(choice(alphabet) for _ in range(5))
    if current_word == "hello":
        break
    elif current_word not in failed_words:
        attempts += 1
        failed_words.add(current_word)

# 记录程序结束时间
end_time = time.time()
# 计算运行时长,保留2位小数
run_duration = round(end_time - start_time, 2)

print(current_word)
print(f"Attempts: {attempts}")
print(f"Total runtime: {run_duration} seconds")

关键修改说明

  • 时长统计实现:

    • 在程序最开始用time.time()记录开始时间,循环结束后再记录一次结束时间,两者的差值就是程序运行总时长。
    • 最后用round()把时长保留两位小数,输出更美观。
  • 代码逻辑优化:

    • 生成5位随机字符串:用''.join(choice(alphabet) for _ in range(5))直接生成,替代原代码里多次append再反复replace的冗余操作,代码更简洁高效。
    • 替换failed_words为集合:原代码用列表存储已尝试字符串,每次检查not in的时间复杂度是O(n);改用集合后,检查时间复杂度降为O(1),当尝试次数较多时,性能提升非常明显。

内容的提问来源于stack exchange,提问作者Riley Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:10:02