我有一個包含大量數據的文件。每一行都是一條記錄。我正在嘗試對整個文件進行一些ETL工作。現在我正在使用標準輸入逐行讀取數據。這很酷的事情是你的腳本可以非常靈活地與其他腳本和shell命令集成。我將結果寫入標準輸出。例如。Python Threading stdin/stdout
$ cat input_file
line1
line2
line3
line4
...
我當前的Python代碼看起來是這樣的 - parse.py
import sys
for line in sys.stdin:
result = ETL(line) # ETL is some self defined function which takes a while to execute.
print result
下面的代碼是它是如何工作現在:
cat input_file | python parse.py > output_file
我已經看過了線程模塊的Python,我想知道如果我使用該模塊,性能會大大提高。
問題1:我該如何規劃每個線程的配額,爲什麼?
...
counter = 0
buffer = []
for line in sys.stdin:
buffer.append(line)
if counter % 5 == 0: # maybe assign 5 rows to each thread? if not, is there a rule of thumb to determine
counter = 0
thread = parser(buffer)
buffer = []
thread.start()
問題2:多線程可能在同一時間打印出結果返回到標準輸出,如何組織他們,避免下面的情況呢?
import threading
import time
class parser(threading.Thread):
def __init__ (self, data_input):
threading.Thread.__init__(self)
self.data_input = data_input
def run(self):
for elem in self.data_input:
time.sleep(3)
print elem + 'Finished'
work = ['a', 'b', 'c', 'd', 'e', 'f']
thread1 = parser(['a', 'b'])
thread2 = parser(['c', 'd'])
thread3 = parser(['e', 'f'])
thread1.start()
thread2.start()
thread3.start()
的輸出是真難看,其中一個行都包含來自兩個線程的輸出。
aFinished
cFinishedeFinished
bFinished
fFinished
dFinished
你能鏈接「Python的線程模塊」嗎? 無論如何,線程訪問一個文件,恕我直言,是不是一件好事。您需要定義什麼內核可以通過鎖和信號量以及作品訪問什麼以及何時訪問。 由於大部分工作是I/O工作,而不是CPU工作,可能你不會看到性能提升。 –