1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #! /usr/bin/python
# Encoding: iso-8859-1
import os
TESTFILE = 'xxxx/doc/bash.html'
def check_file():
"""check we have something to catch"""
lines_found = list()
linecount = 0
with open(TESTFILE, 'r') as f:
for line in f.read().splitlines():
linecount += 1
if line.endswith(os.sep):
lines_found.append(line)
print 'file has %d lines and %d lines ending with %s' %(
linecount, len(lines_found), os.sep)
return lines_found
def brute_force():
"""Pythonic?"""
lines_found = list()
with open(TESTFILE, 'r') as f:
for line in f.read().splitlines():
if line.endswith(os.sep):
lines_found.append(line)
return lines_found
def brute_force_slice():
"""Slice looks to be a real winner"""
lines_found = list()
with open(TESTFILE, 'r') as f:
for line in f.read().splitlines():
if line[-2:-1] == os.sep:
lines_found.append(line)
return lines_found
def endswith_sep():
"""C Way, process line by line"""
lines_found = list()
with open(TESTFILE, 'r') as f:
for line in f:
if line.endswith (os.sep):
lines_found.append(line)
return lines_found
def slice_sep():
"""C Way, with slice"""
lines_found = list()
with open(TESTFILE, 'r') as f:
for line in f:
if line[-2:-1] == os.sep:
lines_found.append(line)
return lines_found
def slice_nosep():
"""C Way, slice & separator in local var"""
y = os.sep
lines_found = list()
with open(TESTFILE, 'r') as f:
for line in f:
if line[-2:-1] == y:
lines_found.append(line)
return lines_found
if __name__ == '__main__':
from timeit import Timer
import operator
COUNT = 20
REPEAT = 5
os.sep = 'e' # mock separator
check_file()
names = ('brute_force', 'brute_force_slice', 'endswith_sep', 'slice_sep', 'slice_nosep' )
results = list()
better = float(sys.maxint)
for name in names:
t = Timer('%s()' % name, "from __main__ import %s" % name)
try:
# ms = 1000 * t.timeit(number=COUNT) / COUNT
ms = 1000 * min(t.repeat(repeat=REPEAT, number=COUNT))/ COUNT
except:
t.print_exc()
sys.exit(1)
print "%-20s : %0.3f Ms" % (name, ms )
results.append((name, ms))
if ms < better:
better = ms
print '--- and the winner is: '
for item in sorted(results,
key=operator.itemgetter(1)):
name, ms = item
print "%-20s : %0.2f%%" % (name, ms/better ) |
Partager