Pyth0nicPenguin Pyth0nicPenguin - 27 days ago 11
Python Question

Make 10,000 random integer tuples quickly

I'm doing a dumb little challenge I got from one of my co-workers;


Make 10,000 random integer tuples, in the same format as a RSA token, in under 30 seconds.


I've successfully done the 10,000 in under 30 seconds but want to know if there's a way to speed this program up a little bit? As of now it averages at about
21.205666701
seconds. From three different runs:


  • On request number: 10000. Done! That took: 19.5520000458 seconds

  • On request number: 10000. Done! That took: 23.8059999943 seconds

  • On request number: 10000. Done! That took: 20.2590000629 seconds



How can I refactor this script and speed up the process time, if I am able to?

import time
import sys
from random import randint


def create_integer_tuple():
return randint(100, 999), randint(100, 999)

if __name__ == '__main__':
strt_time = time.time()
times_done = 0
while True:
with open("challenge_accepted.txt", "a+") as data:
if times_done != 10000:
data.write(str(create_integer_tuple()) + "\n")
times_done += 1
sys.stdout.write("\rOn request number: {}.".format(times_done))
sys.stdout.flush()
else:
print(" Done! That took: {} seconds".format(time.time() - strt_time))
break

Answer
  1. Don't print something on each iteration to stdout (down to 2 seconds)
  2. Move with open("challenge_accepted.txt", "a+") as data: outside of the loop. Why would you always close and reopen the file? (down to 0.06 seconds (with 1.))
Comments