2015-04-04 63 views
0

我想優化我的代碼以在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) 
+1

爲什麼要*當你看到2或3時減少*合計數? – user2357112 2015-04-04 05:57:39

+0

2和3都是素數,但1不是。 – 2015-04-04 06:29:29

+0

是的,但如果輸入只是兩個數字2和3,你看到負兩個複合數字嗎? – user2357112 2015-04-04 06:45:13

回答

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.

+0

「理解比原生Python代碼更快,因爲它們訪問C庫」 - 它們不會比等效循環做得更好。我相信有一些字節碼優化特定於理解和基因組,不能用於等效循環,但沒有提供真正的大規模加速。 – user2357112 2015-04-04 07:12:06

+0

織補。那麼,就像我說的那樣,我希望那裏有一些有用的東西。 – TigerhawkT3 2015-04-04 07:29:35

+0

嗯,我不能添加2和3,因爲我正在閱讀的是隨機數字的.txt文件。我需要測試每個數字,看看它是否是主要的。這就是爲什麼我檢查它是2還是3。 – 2015-04-05 22:12:59