I made a simple program that performs some mathematical operations, and I want to make it faster using multithreading. I understand that Python's GIL prevents true multithreading from taking place, but that there are still situations where the execution time may be improved.
In this case, the threaded and non-threaded execution time of the program seem similar, and so there doesn't appear to be any performance improvement. I'm aware of the multiprocessing module but I want to avoid that due to its limitations when performing shared memory operations. Is there any way I can achieve a significant speed increase in this program using multithreading?
Thanks
import string, random, threading
def getLetters():
letterList = []
for letter in string.ascii_lowercase:
letterList.append(letter)
return letterList
def getNum(letter):
letterVal = ord(letter)
rand = random.randint(1,5000000)
result = 0
for num in range(0,rand):
if num%2 == 0:
result+=num
else:
result-=num
result*=letterVal
print(f"Result: {result}")
return result
def mainWithThreading():
letters = getLetters()
threadList = []
for letter in letters:
th = threading.Thread(target=getNum, args=[letter], daemon=True)
threadList.append(th)
for th in threadList:
th.start()
for th in threadList:
th.join()
def mainWithoutThreading():
letters = getLetters()
for letter in letters:
getNum(letter)
start = time.time()
mainWithoutThreading()
end = time.time()
print(f"Time taken: {end-start:.2f}s\n")
start = time.time()
mainWithThreading()
end = time.time()
print(f"Time taken: {end-start:.2f}s\n")