I've been having an odd behavior in my code when checking for primes. for example
for j in range(3, int(i**0.5)+1, 2):
When using this and only checking for odd numbers, my processes take 0.7401000000000446 mins to complete with 10 million numbers.
meanwhile changing it back to this:
for j in range(2, int(i**0.5)+1, 1):
takes 0.3927166666666987 mins with also 10 million numbers.
what am i doing wrong? i thought going through odd numbers only would result in much faster processing but im getting different results.
here is the full code segment:
import time
import multiprocessing
def prime(i, processes, maxnum, primes):
while maxnum >= i:
f = False
if i <= 1:
i += processes
continue
else:
for j in range(2, int(i**0.5)+1, 1): # i think the bug is in the way [i] is given to processes.
if i % j == 0:
i += processes
f = True
break
if f:
continue
primes.append(i) # append if prime.
# increment by number of processes, example: p1 (i =1) p2 (i=2) up to i = processes, then all jumps by num of processes, check for bugs
i += processes
def test(i):
print("process num: " + str(i))
def main():
start = time.monotonic()
manager = multiprocessing.Manager()
primes = manager.list()
maxnum = 10000000
processes = 16 * 2
plist = []
for i in range(1, processes + 1):
plist.append(multiprocessing.Process(target=prime, args=(i, processes, maxnum, primes,)))
[p.start() for p in plist]
[p.join() for p in plist]
print("time taken: " + str((time.monotonic() - start) / 60) + ' mins')
print(plist)
print(sorted(primes)) #unsure how long does the sorting takes
if __name__ == "__main__": # multiprocessing needs guarding. so all code goes into main i guess
main()