Python 映射需要更快的功能

Python 映射需要更快的功能,python,hadoop,optimization,mapreduce,primes,Python,Hadoop,Optimization,Mapreduce,Primes,我试图优化我的代码以在hadoop集群上运行。有人能帮我找到一些方法让这更好吗?我正在接受一组非常大的数字4000多万,每个数字都在一条新的线上。当我读到数字时,我正在计算每个数字,求和所有数字,同时检查每个数字是否是素数 #!/usr/bin/env python import sys import string import math total_of_primes = 0 total = 0 count = 0 not_prime = 0 count_string = 'Count:'

我试图优化我的代码以在hadoop集群上运行。有人能帮我找到一些方法让这更好吗?我正在接受一组非常大的数字4000多万,每个数字都在一条新的线上。当我读到数字时,我正在计算每个数字,求和所有数字,同时检查每个数字是否是素数

#!/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.

当你看到一个2或3,2和3都是素数时,为什么你要减少合成数的计数,而3是两个素数,但是1不是,是的,但是如果输入只是两个数2和3,你见过两个负数吗?是的,我改了。创建了一个跟踪素数的变量,如果读入2和3,则只需将其添加到该变量中。可以读入的最大数量是多少?理解比本机Python代码快,因为它们访问C库-它们的访问程度不比等效循环高。我相信有一些特定于理解和genexps的字节码优化无法应用于等效循环,但没有提供真正大规模的加速。就像我说的,我希望里面有有用的东西。我不能加2和3,因为我读的是一个随机数的.txt文件。我需要测试每个数字,看看它是否是素数。这就是为什么我要检查它是2还是3。也许你可以在2,3中添加intline,或者在检查非intline%2之前添加intline?如果是2或3,它会立即将其标记为素数,而不检查其他短路条件。