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 99 100 101
| from timeit import Timer
def f():
# code 1
f = open('fifi','r')
ch,x = '',f.readline()
while x:
y = f.readline()
if x=='\n' or y=='\n':
print "Exécution stoppée: le fichier contient une ligne vide"
break
if not y:
print "Il y a un problème: les lignes du fichier ne sont pas en nombre pair."
if x+y not in ch:
ch+=x+y
x = f.readline()
f.close()
b = ch.splitlines()
return b
def g():
# code 2
f = open('fifi','r')
ch,li,x = '',[],f.readline()
while x:
y = f.readline()
if x=='\n' or y=='\n':
print "Exécution stoppée: le fichier contient une ligne vide"
break
if not y:
print "Il y a un problème: les lignes du fichier ne sont pas en nombre pair."
if x+y not in li:
ch+=x+y
li.append(x+y)
x = f.readline()
f.close()
b = ch.splitlines()
return b
def h():
# code 3
f = open('fifi','r')
li,x = [],f.readline()
while x:
y = f.readline()
if x=='\n' or y=='\n':
print "Exécution stoppée: le fichier contient une ligne vide"
break
if not y:
print "Il y a un problème: les lignes du fichier ne sont pas en nombre pair."
if not y.endswith('\n'):
y = y + '\n'
if [x,y] not in li:
li.append([x,y])
x = f.readline()
f.close()
b=[]
[b.extend(u) for u in li]
return b
iterations = 1000
tf = Timer('f()','from __main__ import f').timeit(iterations)
tg = Timer('g()','from __main__ import g').timeit(iterations)
th = Timer('h()','from __main__ import h').timeit(iterations)
print "timeit unique d'execution de f :",tf
print "timeit unique d'execution de g :",tg
print "timeit unique d'execution de h :",th
repet = 8
litf = Timer('f()','from __main__ import f').repeat(repet,iterations)
litg = Timer('g()','from __main__ import g').repeat(repet,iterations)
lith = Timer('h()','from __main__ import h').repeat(repet,iterations)
print "\n\ntemps d'execution de f"
s = 0
for y in litf:
print y
s = s+y
print "temps moyen d'execution de f : ",s/repet
print "\n\ntemps d'execution de g"
s = 0
for y in litg:
print y
s = s+y
print "temps moyen d'execution de g : ",s/repet
print "\n\ntemps d'execution de h"
s = 0
for y in lith:
print y
s = s+y
print "temps moyen d'execution de h : ",s/repet |