Programming/Python

[Python] gzip.open, zcat & pipeline 성능비교

쌍쌍바나나 2018. 10. 20. 12:26
반응형

파이썬에서 gzip파일을 읽는 방법 2가지 성능 비교

gzip 파일 확인

gzip의 파일을 읽으려면 shell에서는 zcat을 이용하면 쉽게 데이터를 확인이 가능하다.

$ zcat * | head -100 $ zcat * | wc -l

아래 소스코드는 zcat과 pipeline을 이용해 읽는 방식과, gzip.open을 이용해 gzip의 파일을 읽는 속도를 비교한 코드이다.

코드

import os
import sys
if sys.version.startswith("3"):
import io
io_method = io.BytesIO
else:
import cStringIO
io_method = cStringIO.StringIO
import gzip
import subprocess
import time
dirname = "test"
fl = os.listdir(dirname)
fl.sort()
ttime = [0, 0]
runs = 5
for i in range(2 * runs):
st = time.time()
for fn in fl:
if not fn.endswith(".gz"):
continue
cc = 0
lc = 0
sz = 0
fullfn = os.path.join(dirname, fn)
sz += os.stat(fullfn)[6]
if i % 2 == 0:
fh = gzip.GzipFile(fullfn, "r")
else:
p = subprocess.Popen(["zcat", fullfn], stdout = subprocess.PIPE)
fh = io_method(p.communicate()[0])
assert p.returncode == 0
for line in fh:
lc += 1
cc += len(line)
et = time.time()
dt = et - st
ttime[i % 2] += dt
print("time-taken = %0.2f seconds, 1000 characters per second = %0.0f, file size per second = %0.0f, character count=%s, line count=%s file size = %s" % (dt, 0.001 * cc / dt, 0.001 * sz / dt, cc, lc, sz))
print("\nAverages")
print(" gzip.open - %0.1f seconds" % (ttime[0] / runs))
print(" zcat and pipe - %0.1f seconds" % (ttime[1] / runs))
view raw gzip_reader.py hosted with ❤ by GitHub

[참고] * https://codebright.wordpress.com/2011/03/25/139/

반응형