ewsd12 发表于 2015-6-1 08:50:59

测试python awk sed 读取文件指定位置时的性能

#!/bin/env python
#coding:utf8


'''
awk 打印指定行数
sed 打印指定行数
python 打印指定位置,某长度字符串

awk 耗时最长,很长
sed awk 时间一半
python 耗时 基本忽略不计


使用脚本监控日志文件的时候,每次记录上次退出的位置
python效率最高.
'''
import os
fromtime import time
from os.path import getsize

testfile='/dev/shm/%s' % time()

#生成文件总行数 10**8 大约800M10**7 大约 80M
linesize=10**7
#提取文件中间行
halfline=int(linesize / 2)
#文件大小一半
halffilesize=0
#测试次数
num=10
#生成文件大小
filesize=0
r=[]

def create_testfile():
        f=open(testfile,'w')
        for i in xrange(linesize):
                f.write(str(i)+'\n')
        f.close()

def time1(func):
        t1=time()
        func()
        t2=time()
        t=t2-t1
        print func.func_name,t
        r.append("%s:\t\t%s" % (func.func_name,str(t) ) )

def awk():
        for i in range(num):
                os.system("/bin/awk 'NR==%s { print $0 }' %s " % (halfline,testfile) )

def sed():
        for i in range(num):
                os.system("/bin/sed -n %sp %s " % (halfline,testfile) )               
                #os.system("/bin/sed -n %sp %s|awk '{print $0}' " % (halfline,testfile) )               
               
def py():
        for i in range(num):
                fn=open(testfile)
                #读取
                fn.seek(halffilesize)
                print fn.read(7)
                fn.close()
               

               
print "create test file!"
create_testfile()       

filesize=getsize(testfile)
halffilesize=int(filesize/2)


time1(awk)
time1(sed)
time1(py)
print "\n\n"
print "halffilesize:\t\t",halffilesize
print "filesize:\t\t",filesize
os.system('/bin/ls -lh %s' % testfile)
print "\t"
for i in r:
        print i
os.unlink(testfile)

国安信仰 发表于 2015-6-26 13:25:12

不错,学习了!
页: [1]
查看完整版本: 测试python awk sed 读取文件指定位置时的性能