2017-03-05 1 views
1

파이썬에서 다중 처리를 허용하기 위해 다음 코드를 분리하려고합니다. 실제로 나에게 실망스러운 작업이되고 있습니다. 다중 처리에 익숙하지 않고 문서를 읽고 많은 샘플을 읽었습니다. 찾아 내고 그러나 한 번에 모든 cpu 중핵에 작동 할 해결책을 찾아 내지 않았다.파이썬에서 iterable을 다중 처리하기

iterables를 분기로 분할하고 parrallel에서 테스트를 수행하고 싶습니다.

내 단일 스레드 예 :

import itertools as it 
import numpy as np 

wmod = np.array([[0,1,2],[3,4,5],[6,7,3]]) 
pmod = np.array([[0,1,2],[3,4,5],[6,7,3]]) 

plines1 = it.product(wmod[0],wmod[1],wmod[2]) 
plines2 = it.product(pmod[0],pmod[1],pmod[2]) 

check = .915 
result = [] 

for count, (A,B) in enumerate(zip(plines1,plines2)): 
    pass 

    test = (sum(B)+10)/(sum(A)+12) 
    if test > check: 
     result = np.append(result,[A,B]) 
print('results: ',result) 

나는이 3 × 3 행렬의 한 쌍의 아주 작은 예입니다 실현,하지만 난 큰 행렬의 쌍에 적용, 그리고 약 걸릴 것 계산하는 데 1 시간. 주어진 충고에 감사드립니다.

+0

글쎄, 한 가지만 들어, 나는 당신의 루프 내부에서'result = np.append (result, [A, B])'를 취할 것이다. 왜'list'보다는 numpy 배열을 사용하고 있습니까? 이와 같이 추가하면 배열과 배열이 매우 비효율적입니다. 이상한 것은'result = []'도 사용하는 것입니다 ... –

+0

확장 성과 효율성을 위해 numpy를 사용하기로 결정했습니다. 앞서 말했듯이, 3x3 행렬은 예제에 불과합니다. for 루프는 반복입니다. 어떻게 든 검색하지 않으면 데이터가 유지되지 않습니다. –

+0

예,하지만'numpy'는 마술처럼 코드를 확장 성있게 만들지 않습니다. 이와 같이 numpy를 사용하면 반대의 효과가 있습니다. –

답변

0

반복문을 덤프하기 위해 대기열을 사용하는 것이 좋습니다. 다음과 같은 것 :

import multiprocessing as mp 
import numpy as np 
import itertools as it 


def worker(in_queue, out_queue): 
    check = 0.915 
    for a in iter(in_queue.get, 'STOP'): 
     A = a[0] 
     B = a[1] 
     test = (sum(B)+10)/(sum(A)+12) 
     if test > check: 
      out_queue.put([A,B]) 
     else: 
      out_queue.put('') 

if __name__ == "__main__": 
    wmod = np.array([[0,1,2],[3,4,5],[6,7,3]]) 
    pmod = np.array([[0,1,2],[3,4,5],[6,7,3]]) 

    plines1 = it.product(wmod[0],wmod[1],wmod[2]) 
    plines2 = it.product(pmod[0],pmod[1],pmod[2]) 

    # determine length of your iterator 
    counts = 26 

    # setup iterator 
    it = zip(plines1,plines2) 

    in_queue = mp.Queue() 
    out_queue = mp.Queue() 

    # setup workers 
    numProc = 2 
    process = [mp.Process(target=worker, 
          args=(in_queue, out_queue), daemon=True) for x in range(numProc)] 

    # run processes 
    for p in process: 
     p.start() 

    results = [] 
    control = True 

    # fill queue and get data 
    # code fills the queue until a new element is available in the output 
    # fill blocks if no slot is available in the in_queue 
    for idx in range(counts): 
     while out_queue.empty() and control: 
      # fill the queue 
      try: 
       in_queue.put(next(it), block=True) 
      except StopIteration: 
       # signals for processes stop 
       for p in process: 
        print('stopping') 
        in_queue.put('STOP') 
       control = False 
       break 
     results.append(out_queue.get(timeout=10)) 

    # wait for processes to finish 
    for p in process: 
     p.join() 

    print(results) 

    print('finished') 

그러나 작업 목록의 길이를 먼저 결정해야합니다.

+0

내 프로젝트에 구현하기 전에 모든 코드를 이해하려고 시도하지만 샘플을 실행하려고하면 int 객체가 반복 가능하지 않다는 오류가 발생합니다. –

+0

그가 불평하는 라인을 지적 할 수 있습니까? 어쩌면 문제를 일으키는 '노동자'기능 일 수도 있습니다. '테스트의 단순한 print-command insteat를 넣으십시오. – RaJa

+0

실습 예제 나 테스트 기능으로 제 답을 바로 잡았습니다. 그것은 내 파이썬 3.5에서 오류없이 실행됩니다. – RaJa

관련 문제