반응형
파이썬에서 gzip파일을 읽는 방법 2가지 성능 비교
gzip 파일 확인
gzip의 파일을 읽으려면 shell에서는 zcat을 이용하면 쉽게 데이터를 확인이 가능하다.
$ zcat * | head -100
$ zcat * | wc -l
아래 소스코드는 zcat과 pipeline을 이용해 읽는 방식과, gzip.open을 이용해 gzip의 파일을 읽는 속도를 비교한 코드이다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
[참고] * https://codebright.wordpress.com/2011/03/25/139/
반응형
'Programming > Python' 카테고리의 다른 글
[Python] Pandas csv를 dataframe으로 읽고 쓰는 방법 (0) | 2018.10.20 |
---|---|
[Python] Jupyter matplot한글 깨짐 현상 (0) | 2018.10.20 |
[Python] 튜블 정렬 하는 방법 (0) | 2018.10.20 |
[Python] 쥬피터(jupyter) 노트북 백그라운드로 실행 (0) | 2018.10.20 |
[Python] 사전에서 값을 기준으로 topK를 추출하는 방법 (0) | 2018.10.20 |