我正在制作一个素数计算器,它的工作原理非常完美,但我希望通过使用多线程来加快速度。我想知道你们中的任何一个人是否可以用某些资源指向我的某个地方(python文档不是很有帮助),或者在我的代码中给我一个例子。制作程序多线程
import time
#Set variables
check2 = 0
check3 = 0
check5 = 0
check7 = 0
#get number
primenum = int(input("What number do you want to find out whether it is prime or not?\nIt must be a natural number\n**Calculations may take some time depending of the power of the computer and the size of the number**\n"))
#set divisor
primediv = primenum - 2
#assume it's prime until proven innocent
prime = 1
#Create variable for GUI
working = "Calculating"
work = 10000000
#set the number of divides to 0
divnum = 0
#start the clock
starttime = time.perf_counter()
#until it is not prime or divided by 1...
while prime == 1 and primediv >7:
#does simple checks to deal with large numbers quickly
#Does this by dividing with small numbers first
if primenum != 0 and check2 == 0:
primemod = primenum % 2
check2 = 1
print(working + ".")
working = working +"."
elif primenum != 0 and check3 == 0:
primemod = primenum % 3
check3 = 1
print(working + ".")
working = working +"."
elif primenum != 0 and check5 == 0:
primemod = primenum % 5
check5 = 1
print(working + ".")
working = working + "."
elif primenum != 0 and check7 == 0:
primemod = primenum % 7
check7 = 1
print(working + ".")
working = working + "."
#divde and get remainder
else:
primemod = primenum % primediv
#Working visuals
if divnum == work:
print(working + ".")
working = working +"."
work = work + 10000000
#if the can't be devided evenly
if primemod == 0:
#then it isn't a prime
prime = 0
else:
#if it can, keep going
primediv = primediv - 2
divnum = divnum + 1
#print results
if prime == 1:
print("That number is prime")
print ("It took ", time.perf_counter()-starttime, " seconds to perform that calculation\n")
else:
print("That number is not prime")
print ("It took ", time.perf_counter()-starttime, " seconds to perform that calculation\n")
你可以开始[这里](http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies),[这里](http://stackoverflow.com/questions/11899224/multithreading-in -python)和[here](http://stackoverflow.com/questions/6469462/python-multithreading)。 :) – Manhattan
请注意,多线程(Python)不会使任何东西运行更快。它不使用多个处理器线程,它只运行在多个操作线程中。 –
同时深入研究[Eratosthenes的筛选器](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)进行素数检查。它比你的强力方法指数更快。 –