測試python awk sed 讀取檔案指定位置時的效能

來源:互聯網
上載者:User

標籤: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 讀取檔案指定位置時的效能

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.