-
Notifications
You must be signed in to change notification settings - Fork 10
/
profileDecorators.py
62 lines (46 loc) · 1.38 KB
/
profileDecorators.py
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
import cProfile as prof
import pstats
import os
import time
def d_profile(f):
'''
writes out profiling info on the decorated function. the profile results are dumped in a file
called something like "_profile__<moduleName>.<functionName>.txt"
'''
def newFunc( *a, **kw ):
def run(): f( *a, **kw )
baseDir = os.path.split( __file__ )[0]
tmpFile = os.path.join( baseDir, 'profileResults.tmp' )
prof.runctx( 'run()', globals(), locals(), tmpFile )
try:
module = f.__module__
except AttributeError:
module = 'NOMODULE'
dumpFile = os.path.join( baseDir, '_profile__%s.%s.txt' % (module, f.__name__) )
dumpF = file( dumpFile, 'w' )
stats = pstats.Stats( tmpFile )
stats.sort_stats( 'time', 'calls', 'name' )
stats.stream = dumpF
stats.print_stats()
stats.sort_stats( 'cumulative', 'time' )
stats.print_stats()
dumpF.close()
#remove the tmpFile
os.remove( tmpFile )
print 'LOGGED PROFILING STATS TO', dumpFile
newFunc.__name__ = f.__name__
newFunc.__doc__ = f.__doc__
return newFunc
def d_timer(f):
'''
simply reports the time taken by the decorated function
'''
def newFunc( *a, **kw ):
s = time.clock()
ret = f( *a, **kw )
print 'Time Taken by %s: %0.3g' % (f.__name__, time.clock()-s)
return ret
newFunc.__name__ = f.__name__
newFunc.__doc__ = f.__doc__
return newFunc
#end