2017-08-21 12 views
0

私はしばらく見回してきましたが、私の問題を解決する可能性のある例を見つけることはできませんでした。私は自分のコードから例を追加しました。これは遅いことに気付くことができ、2つの機能を別々に行うことができます。whileループでのPythonの並列計算

私の目標は、毎秒最新のパラメータ値を印刷することです。同時に、遅いプロセスはバックグラウンドで計算することができます。最新の値が表示され、プロセスが準備完了になると値が更新されます。

もっと良い方法をお勧めしますか?例が本当に役立つでしょう。

ありがとうございます。

import time 

def ProcessA(parA): 
    # imitate slow process 
    time.sleep(5) 
    parA += 2 

    return parA 

def ProcessB(parB): 
    # imitate slow process 
    time.sleep(10) 
    parB += 5 

    return parB 

# start from here 
i, parA, parB = 1, 0, 0 

while True: # endless loop 
    print(i) 
    print(parA) 
    print(parB) 

    time.sleep(1) 
    i += 1 

    # update parameter A 
    parA = ProcessA(parA) 

    # update parameter B 
    parB = ProcessB(parB) 
+0

最も直接的な方法はおそらくスレッドを使用することです。 ['threading'](https://docs.python.org/3.6/library/threading.html#module-threading)モジュールを見てください。 –

答えて

0

これはあなたのために行うべきだと思います。これはあなたが持っているコアの数に等しい合計まで余分なパラレル関数を追加できるという利点があります。編集は大歓迎です。

#import time module 
import time 

#import the appropriate multiprocessing functions 
from multiprocessing import Pool 

#define your functions 
#whatever your slow function is 
def slowFunction(x): 
    return someFunction(x) 

#printingFunction 
def printingFunction(new,current,timeDelay): 
    while new == current: 
     print current 
     time.sleep(timeDelay) 


#set the initial value that will be printed. 
#Depending on your function this may take some time. 
CurrentValue = slowFunction(someTemporallyDynamicVairable) 

#establish your pool 
pool = Pool() 

while True: #endless loop 

    #an asynchronous function, this will continue 
    # to run in the background while your printing operates. 
    NewValue = pool.apply_async(slowFunction(someTemporallyDynamicVairable)) 

    pool.apply(printingFunction(NewValue,CurrentValue,1)) 

    CurrentValue = NewValue 

#close your pool 
pool.close()