Python 使循环 运行 更快

Python make loops run faster

我做了一个简单的Python3.9程序:

attemptedPass = 0
password = 1234
while True:
    if attemptedPass == password:
        print("PASSWORD FOUND")
        break
    attemptedPass += 1
    print(attemptedPass)

它基本上会尝试多个密码,直到找到正确的密码。

问题是:当 运行 它通过 Visual Studio 2022 年时,它运行得非常快(它在大约 15 秒内找到我的 6 位密码)。但是,当 运行 它通过双击文件时,它运行很慢。这是什么原因,我该如何解决?

当存在 print(attemptedPass) 时,您可以将 windows powershell 的默认缓冲区从 8192 增加到 2*8192,以大致匹配 mvs2022 性能。

代码

import time
import io
import sys
import statistics as stats


def speed_test():
    t0 = time.perf_counter()
    attemptedPass = 0
    password = 1234567

    while True:
        if attemptedPass == password:
            print("PASSWORD FOUND")
            break
        attemptedPass += 1
        print(attemptedPass)  

    return time.perf_counter() - t0  # sec


def main():
    newbufsize = io.DEFAULT_BUFFER_SIZE * 2
    sys.stdout = io.TextIOWrapper(io.BufferedWriter(sys.stdout.buffer, buffer_size=newbufsize))
    data = []
    for _ in range(4):
        e = speed_test()
        data.append(round(e, 1))

    print(data)
    print(f'mean: {round(stats.mean(data), 1)}')

main()

输出

Windows powershell

[18.8, 18.8, 18.8, 18.8]
mean: 18.8

有无mvs2022

sys.stdout = io.TextIOWrapper(io.BufferedWriter(sys.stdout.buffer, buffer_size=newbufsize))
[20.9, 20.9, 20.9, 20.9]
mean: 20.9