我怎样才能加快这个 python 代码的速度?
How can I speed this python code up?
我已经编写了一些计算素数的代码(我知道没什么特别的)并且正如预期的那样它会减慢数字越大,我知道无论数字如何都不可能使其速度相同但我敢肯定我可以提高它的速度,我只是不知道如何...
import time
number = 1000000001
count = 0
start = time.time()
while number > 1000000000 and number < 10000000000000:
for i in range(1, round(number/2 + 1)):
if (number / i).is_integer():
count += 1
if count > 1:
break
if count < 2:
print(str(number) + ' prime')
number = number + 1
count = 0
end = time.time()
print(end - start)
几件事:
- 您不必检查
1
,但 3
、5
和所有 奇数 数字;
- 在n/2之前你不必检查,但你可以在sqrt(n);
- 不要使用除法,因为那时你使用浮点数,但使用
%
检查模数;
- 你只需要检查奇数(或两个);和
- 您可以省略 while 循环中的大于检查,因为数字只会递增。
所以改进的版本是:
import time
<b>from math import sqrt # import square root</b>
start = time.time()
<b>for number in range(1000000001,10000000000000,2): # use for, hops of 2</b>
<b>for i in range(3, int(sqrt(number))+1,2): # check 3, 5,... up to sqrt(n)</b>
<b>if number % i == 0: # use modulo checks instead of floating point</b>
break
<b>else: # use a for-else structure for faster ending</b>
print(str(number) + ' prime')
count = 0
end = time.time()
print(end - start)
然而,Python 并不是为了充分利用 CPU 而设计的。如果你真的想编写一个超级优化的算法,你将不得不选择一种更快(但不太方便)的编程语言。
我已经编写了一些计算素数的代码(我知道没什么特别的)并且正如预期的那样它会减慢数字越大,我知道无论数字如何都不可能使其速度相同但我敢肯定我可以提高它的速度,我只是不知道如何...
import time
number = 1000000001
count = 0
start = time.time()
while number > 1000000000 and number < 10000000000000:
for i in range(1, round(number/2 + 1)):
if (number / i).is_integer():
count += 1
if count > 1:
break
if count < 2:
print(str(number) + ' prime')
number = number + 1
count = 0
end = time.time()
print(end - start)
几件事:
- 您不必检查
1
,但3
、5
和所有 奇数 数字; - 在n/2之前你不必检查,但你可以在sqrt(n);
- 不要使用除法,因为那时你使用浮点数,但使用
%
检查模数; - 你只需要检查奇数(或两个);和
- 您可以省略 while 循环中的大于检查,因为数字只会递增。
所以改进的版本是:
import time
<b>from math import sqrt # import square root</b>
start = time.time()
<b>for number in range(1000000001,10000000000000,2): # use for, hops of 2</b>
<b>for i in range(3, int(sqrt(number))+1,2): # check 3, 5,... up to sqrt(n)</b>
<b>if number % i == 0: # use modulo checks instead of floating point</b>
break
<b>else: # use a for-else structure for faster ending</b>
print(str(number) + ' prime')
count = 0
end = time.time()
print(end - start)
然而,Python 并不是为了充分利用 CPU 而设计的。如果你真的想编写一个超级优化的算法,你将不得不选择一种更快(但不太方便)的编程语言。