我正在做一个素数计算器,它工作得很完美,但我希望它通过多线程的使用更快。我想知道你们中是否有人能给我指出一些有资源的地方(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")
最流行的Python实现(CPython和PyPy)都带有全局解释器锁(“GIL”)。这样做的目的基本上是为了简化内存管理。它的效果是每次只有一个线程可以执行Python字节码。所以对于一个用Python完成所有计算的程序来说,线程并不能使它更快。在
通常,使程序更快的最好方法是找到更好的算法。看看这个:
(1)偶数>;2可以除以2,因此它们不能是素数,也不需要考虑。在
(2):要使奇数}对所有先前奇数(
c
为素数,必须确保{p
)的模必须是非零的。在(3):2也是质数。在
一个小的改进是
^{pr2}$p
只需要上升到sqrt(c)
。在请注意,我使用的是列表理解而不是for循环,因为它们通常更快。在
最后,亚当·斯密提到的一种筛子
为了看哪个更快,我们需要运行测试
首先是
num=100
。在然后1000:
然后是10000
在这些算法中,
prime_list2
似乎是最有效的。在相关问题 更多 >
编程相关推荐