What my code does is generate an X amount of random lines, each is the length of X
My program is almost finished but I couldn't get the time to work, more specifically, get it out of the function, I know it calculates the time correctly because if I put a print in the break section it actually prints the time, but when I want to use it outside the function it never is defined
I tried tons of stuff, like globalizing it in the function, outside function (it doesn't change from 0, which means the function is not changing the variable for some reason) , tried float, tried adding the line elapsed = MainCode() , but all never working, I spent like 6 hours with this single issue, 3 of those hours with other programmers from Python's official discord server for extra help, all were also confused as to why is it still not considered defined
here's my full code, any help is appreciated
import random
import string
import multiprocessing
import os
import sys
import time
if __name__ == "__main__":
lines_wanted = input("input how many lines: ") #user can input how many lines he wants
length = input("How long: ") #user can enter how long each line should be
def MainCode(lines_wanted, length):
global elapsed
elapsed = 0.0
starttime = time.time() # start the time
file = open("blablabla.txt", "a",) # open/create the file
i = 0
while 1 == 1:
file.write(''.join(random.choice(string.ascii_letters + string.digits + ".") for i in range(int(length))) + "\n") # write the randomly generated lowercase string
i += 1 * multiprocessing.cpu_count() # count how many lines the loop is on
if i >= int(lines_wanted): # If it reaches the lines it would stop writing
endtime = time.time() # stop the time
elapsed = endtime - starttime #calculate the time
return elapsed
break
processes = []
if __name__ == '__main__':
for _ in range(multiprocessing.cpu_count()):
p = multiprocessing.Process(target=MainCode, args=(lines_wanted, length))
p.start()
processes.append(p)
for process in processes:
process.join()
elapsee = MainCode()
if __name__ == "__main__": # Prints this after finshing the func above
print(f"Finished Writting {lines_wanted} lines, took {elapsee:.1f} to generate")
1 == 1is an arbitrary way of writingTrue.