码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-31 06:55:42      阅读:233      评论:0      收藏:0      [点我收藏+]

标签: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 读取文件指定位置时的性能

标签:python   sed   awk   字符串   记录   监控   

原文地址:http://focusonit.blog.51cto.com/10134721/1656694

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!