需要更快的地图功能

时间:2015-04-04 05:40:23

标签: 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:'
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)

1 个答案:

答案 0 :(得分:0)

我试图把所有东西都变成一种理解。理解比本机Python代码更快,因为它们访问C库。我也省略了23的测试,因为您可以在完成循环后手动添加这些测试。

我几乎可以保证这会有错误,因为我没有你的测试数据和这么大的理解(对我来说,无论如何)真的需要测试。它在技术上是一个单行,但我试图将其拆分以便于阅读。但是,希望它至少能给你一些想法。

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语言。