標籤:python sed awk 字串 記錄 監控
#!/bin/env python
#coding:utf8
‘‘‘
awk 列印指定行數
sed 列印指定行數
python 列印指定位置,某長度字串
awk 耗時最長,很長
sed awk 時間一半
python 耗時 基本忽略不計
使用指令碼監控記錄檔的時候,每次記錄上次退出的位置
python效率最高.
‘‘‘
import os
from time import time
from os.path import getsize
testfile=‘/dev/shm/%s‘ % time()
#組建檔案總行數 10**8 大約800M 10**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)
測試python awk sed 讀取檔案指定位置時的效能