user17780528
user17780528

Reputation:

Python make loops run faster

I have made a simple Python 3.9 program:

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

which basically tries multiple passwords until it finds the correct one.

The problem is: when running it through Visual Studio 2022, it runs extremely fast (it finds my 6-digit password in about 15 seconds). But, when running it by double-clicking the file, it runs very slowly. What is the reason for that and how can I fix it?

Upvotes: 0

Views: 78

Answers (1)

ferdy
ferdy

Reputation: 5014

When there is print(attemptedPass) you can increase the default buffer from 8192 to 2*8192 for windows powershell to approximately match the mvs2022 performance.

Code

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()

Output

Windows powershell

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

mvs2022 with or without

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

Upvotes: 0

Related Questions