시간이 오래 걸리는 태깅 작업을 수행하다보면 지루해지곤합니다. 그럴 때는 병렬처리 기법을 적용해보면 어떨까요? 파이썬은 멀티쓰레딩과 멀티프로세싱을 지원하며, 물론 그를 KoNLPy에 적용할 수 있습니다. 다음은 멀티쓰레딩을 활용한 예시입니다.
#! /usr/bin/python2.7
# -*- coding: utf-8 -*-
from konlpy.tag import Kkma
from konlpy.corpus import kolaw
from threading import Thread
import jpype
def do_concurrent_tagging(start, end, lines, result):
jpype.attachThreadToJVM()
l = [k.pos(lines[i]) for i in range(start, end)]
result.append(l)
return
if __name__=="__main__":
import time
print('Number of lines in document:')
k = Kkma()
lines = kolaw.open('constitution.txt').read().splitlines()
nlines = len(lines)
print(nlines)
print('Batch tagging:')
s = time.clock()
result = []
l = [k.pos(line) for line in lines]
result.append(l)
t = time.clock()
print(t - s)
print('Concurrent tagging:')
result = []
t1 = Thread(target=do_concurrent_tagging, args=(0, int(nlines/2), lines, result))
t2 = Thread(target=do_concurrent_tagging, args=(int(nlines/2), nlines, lines, result))
t1.start(); t2.start()
t1.join(); t2.join()
m = sum(result, []) # Merge results
print(time.clock() - t)
출력 결과:
Number of lines in document:
356
Batch tagging:
37.758173
Concurrent tagging:
8.037602
얼마나 빨라지는지 보세요!
주석