ATLAS Offline Software
Loading...
Searching...
No Matches
AtlRunQueryTimer.py
Go to the documentation of this file.
1# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
2
3
4from contextlib import contextmanager
5from time import time
6
8 def __init__(self, name):
9 self.name = name
10 self.totaltime = 0
11 self.subcounts = []
12
13 def __repr__(self):
14 return "%s: %f" % (self.name, self.totaltime)
15
16 def __str__(self):
17 return "%s: %f" % (self.name, self.totaltime)
18
19 def printRecursive(self, lvl):
20 from operator import attrgetter
21 # print myself
22 if self.subcounts:
23 # sum up sub counts
24 ts = sum([x.totaltime for x in self.subcounts])
25 print ("%s%-70s : %f (sub sum %f)" % (5*lvl*" ", self.name, self.totaltime, ts))
26 else:
27 print ("%s%-70s : %f" % (5*lvl*" ", self.name, self.totaltime))
28 # sort sub counters
29 sortedByTime = sorted(self.subcounts,key=attrgetter('totaltime'),reverse=True)
30 # call print for sub counters
31 for subtc in sortedByTime:
32 subtc.printRecursive(lvl+1)
33
34 #def __eq__(self, r):
35 # return self.name == r
36
37
39 level=0
40 total = TimeCount('total')
41 totalFlat = {}
42 context = []
43
44 @classmethod
45 def saveTimeFlat(cls, exectime):
46 n = cls.context[-1]
47 if n not in cls.totalFlat:
48 cls.totalFlat[n] = [0,0]
49 cls.totalFlat[n][0] += exectime
50 cls.totalFlat[n][1] += 1
51
52
53 @classmethod
54 def saveTime(cls, exectime):
55 cur = cls.total # a TimeCount instance
56 for n in cls.context:
57 if n=='total':
58 cur = cls.total
59 continue
60 try:
61 idx = cur.subcounts.index(n)
62 print ('index', idx)
63 cur = cur.subcounts[idx]
64 except ValueError:
65 cur.subcounts += [TimeCount(n)]
66 cur = cur.subcounts[-1]
67 cur.totaltime += exectime
68 cls.saveTimeFlat(exectime)
69
70 @classmethod
72 #import pickle
73 #f = open("timecount.pickle","w")
74 #pickle.dump(cls.total,f)
75 #f.close()
76 cls.total.printRecursive(0)
77
78 @classmethod
79 def printTimeFlat(cls):
80 for name, [_time, callcount] in sorted(cls.totalFlat.items(),key=lambda x: x[1][0]):
81 print ("%-70s : %f (%i)" % (name, _time, callcount))
82
83
84@contextmanager
85def timer(name, disabled = False):
86 "A context manager which spits out how long the block took to execute"
87 if disabled: #not environ.has_key("ARQDEBUG"):
88 yield
89 return
90
91 from CoolRunQuery.utils.AtlRunQueryTimer import TimerStats as TS
92
93 start = time()
94 TS.level += 1
95 TS.context.append(name)
96 try:
97 yield
98 finally:
99 end = time()
100 execTime = end - start
101 TS.saveTime(execTime)
102 TS.level -= 1
103 TS.context.pop()
104 print ("%*s took %.2f sec to %s" % (5*TS.level, "...", execTime, name))
timer(name, disabled=False)