需要更快的地图功能
我想优化我的代码以在hadoop集群上运行。任何人都可以帮助我找到一些方法来改善这一点吗?我正在接受一组数量超过四千万的数字,每个数字都在一个新的线上。随着数字读入我计算每个数字,总结所有数字,并检查每个数字,看看它是否是一个素数。需要更快的地图功能
#!/usr/bin/env python
import sys
import string
import math
total_of_primes = 0
total = 0
count = 0
not_prime = 0
count_string = 'Count:'
total_string = 'Total:'
prime_string = 'Number of Primes:'
for line in sys.stdin:
try:
key = int(line)
except:
continue
total = total + key
count = count + 1
if key == 2 or key == 3:
not_prime = not_prime - 1
elif key%2 == 0 or key%3 == 0:
not_prime = not_prime + 1
else:
for i in range(5,(int(math.sqrt(key))+1),6):
if key%i == 0 or key%(i+2) ==0:
not_prime = not_prime + 1
break
total_of_primes = count - not_prime
print '%s\t%s' % (count_string,count)
print '%s\t%s' % (total_string,total)
print '%s\t%s' % (prime_string,total_of_primes)
我试着把一切都变成理解。理解比原生Python代码更快,因为他们访问C库。我也省略了2
和3
的测试,因为您可以在完成循环后手动添加这些测试。
我几乎可以保证这会有错误,因为我没有你的测试数据,并且对于我来说(对我来说)这个大的理解真的需要测试。这在技术上是一个单线,但我试图将其拆分为可读性。不过,希望至少能给你一些想法。
biglist = [ # this will be a list of booleans
not int(line)%2 or # the number is not even
not int(line)%3 or # not divisible by 3
(
not int(line)%i or # not divisible by each item in the range() object
not int(line)%(i+2) for i in # nor by 2 greater than each item
# and only go through the range() object while it's still prime
itertools.takewhile(lambda x: not int(line)%x or not int(line)%(x+2),
range(5, int(pow(int(line), 0.5))+1, 6)) # pow(x, 0.5) uses a built-in instead of an imported module
)
for line in sys.stdin) if line.lstrip('-+').isdigit() # going through each item in sys.stdin
# as long as long as it's a digit. if you only expect positive numbers, you can omit ".lstrip('-+')".
]
total_of_primes = len(biglist) + 2 # manually add 2 and 3 instead of testing it
如果你不能得到执行时间下来远远不够,你可能会考虑迁移到较低级别(慢写,运行更快)的语言,像C.
“理解比原生Python代码更快,因为它们访问C库” - 它们不会比等效循环做得更好。我相信有一些字节码优化特定于理解和基因组,不能用于等效循环,但没有提供真正的大规模加速。 – user2357112 2015-04-04 07:12:06
织补。那么,就像我说的那样,我希望那里有一些有用的东西。 – TigerhawkT3 2015-04-04 07:29:35
嗯,我不能添加2和3,因为我正在阅读的是随机数字的.txt文件。我需要测试每个数字,看看它是否是主要的。这就是为什么我检查它是2还是3。 – 2015-04-05 22:12:59
为什么要*当你看到2或3时减少*合计数? – user2357112 2015-04-04 05:57:39
2和3都是素数,但1不是。 – 2015-04-04 06:29:29
是的,但如果输入只是两个数字2和3,你看到负两个复合数字吗? – user2357112 2015-04-04 06:45:13