CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
parserTimingReport.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import sys
3 import math
4 import re
5 from cmssw_exportdb_xml import *
6 from FileNamesHelper import *
7 
8 """
9 Performance profiling:
10  ncalls tottime percall cumtime percall filename:lineno(function)
11  1 0.000 0.000 71.618 71.618 <stdin>:1(foo)
12  1 0.315 0.315 71.933 71.933 <string>:1(<module>)
13  1 47.561 47.561 71.618 71.618 parserTimingReport.py:27(loadTimeLog)
14  8000 0.191 0.000 0.343 0.000 parserTimingReport.py:8(extractRSS_VSIZE)
15  1 0.000 0.000 0.000 0.000 {len}
16  2384000 3.239 0.000 3.239 0.000 {method 'append' of 'list' objects}
17  1 0.000 0.000 0.000 0.000 {method 'close' of 'file' objects}
18  1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
19  24000 0.041 0.000 0.041 0.000 {method 'partition' of 'str' objects}
20  2392000 5.804 0.000 5.804 0.000 {method 'split' of 'str' objects}
21  10791332 14.782 0.000 14.782 0.000 {method 'strip' of 'str' objects}
22  1 0.000 0.000 0.000 0.000 {method 'xreadlines' of 'file' objects}
23  1 0.000 0.000 0.000 0.000 {open}
24 
25 """
26 
27 
28 """ given two lines returns the VSIZE and RSS values along with event number """
29 def extractRSS_VSIZE(line1, line2, record_number):
30  """
31  >>> extractRSS_VSIZE("%MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1", \
32  "MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0")
33  (('1', '760.25'), ('1', '923.07'))
34  """
35 
36  if ("Run" in line1) and ("Event" in line1): # the first line
37  event_number = line1.split('Event:')[1].strip()
38  else: return False
39 
40  """ it's first or second MemoryCheck line """
41  if ("VSIZE" in line2) and ("RSS" in line2): # the second line
42  RSS = line2.split("RSS")[1].strip().split(" ")[0].strip() #changed partition into split for backward compatability with py2.3
43  VSIZE = line2.split("RSS")[0].strip().split("VSIZE")[1].strip().split(" ")[0].strip()
44  #Hack to return the record number instea of event number for now... can always switch back of add event number on top
45  #return ((event_number, RSS), (event_number, VSIZE))
46  return ((record_number, RSS), (record_number, VSIZE))
47  else: return False
48 
49 
50 def loadTimeLog(log_filename, maxsize_rad = 0): #TODO: remove maxsize to read, used for debugging
51  """ gets the timing data from the logfile
52  returns 4 lists:
53 
54  * ModuleTime data (event_number, module_label, module_name, seconds) and
55  * EventTime data
56  - with granularity of event (initial - not processed data)
57  * RSS per event
58  * VSIZE per event
59  """
60  # ----- format of logfile ----
61  # Report columns headings for modules: eventnum runnum modulelabel modulename timetakeni"
62  # e.g. TimeModule> 1 1 csctfDigis CSCTFUnpacker 0.0624561
63 
64  mod_data = []
65  evt_data = []
66  rss_data = []
67  vsize_data = []
68  # open file and read it and fill the structure!
69  logfile = open(log_filename, 'r')
70 
71  # get only the lines which have time report data
72  #TODO: reading and processing line by line might speed up the process!
73 
74  memcheck_line1 = False
75 
76  record_number=0
77  last_record=0
78  last_event=0
79  for line in logfile.xreadlines():
80  if 'TimeModule>' in line.strip():
81  line = line.strip()
82  line_content_list = line.split(' ')[0:]
83  #Hack to avoid issues with the non-consecutive run numbers:
84  event_number = int(line_content_list[1])
85  if event_number != last_event:
86  record_number=record_number+1
87  last_event=event_number
88  # module label and name were mixed up in the original doc
89  module_label = str(line_content_list[4])
90  module_name = str(line_content_list[3])
91  seconds = float(line_content_list[5])
92  #For now let's try to switch to the record_number... if we need to also have the event_number we can always add it back.
93  #mod_data.append((event_number, module_label, module_name, seconds))
94  mod_data.append((record_number, module_label, module_name, seconds))
95  if 'TimeEvent>' in line.strip():
96  line = line.strip()
97  line_content_list = line.split(' ')[0:]
98  #Hack to avoid issues with the non-consecutive run numbers:
99  event_number = int(line_content_list[1])
100  if event_number != last_event:
101  record_number=record_number+1
102  last_event=event_number
103  # module label and name were mixed up in the original doc
104  time_seconds = str(line_content_list[3])
105 
106  #TODO: what are the other [last two] numbers? Real time? smf else? TimeEvent> 1 1 15.3982 13.451 13.451
107  #For now let's try to switch to the record_number... if we need to also have the event_number we can always add it back.
108  #evt_data.append((event_number, time_seconds))
109  evt_data.append((record_number, time_seconds))
110  """
111  %MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1
112  MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0
113  """
114  if 'MemoryCheck:' in line.strip():
115  # this is the first line out of two
116  if (not memcheck_line1):
117  memcheck_line1 = line.strip()
118  else:
119  #FIXME (eventually)
120  #Hacking in the record_number extracted from the TimeEvent and TimeModule parsing... NOT ROBUST...
121  (rss, vsize) = extractRSS_VSIZE(memcheck_line1, line.strip(), record_number)
122  rss_data.append(rss)
123  vsize_data.append(vsize)
124  else:
125  memcheck_line1 = False
126 
127  logfile.close()
128 
129  return (mod_data, evt_data, rss_data, vsize_data)
130 
131 
132 
133 
134 def calcRMS(items,avg):
135  """ returns RootMeanSquare of items in a list """
136  # sqrt(sum(x^2))
137  # Not statistics RMS... "physics" RMS, i.e. standard deviation: sqrt(sum((x-avg)**2)/N)
138  # return math.sqrt(reduce(lambda x: (x - avg)**2, items) / len(items))
139  return math.sqrt(sum([(x-avg)**2 for x in items])/len(items))
140 
141 def calc_MinMaxAvgRMS(items, remove_first = True, f_time = lambda x: x[0], f_evt_num = lambda x: x[1],):
142  """ returns a dict of avg, min, max, rms """
143  # save the cpu time of first event before removing the first result!
144  cpu_time_first = f_time(items[0])
145 
146  if len(items) > 1 and remove_first == True:
147  items.remove(items[0]) #TODO: if there is only one event - we have a problem -> do we eliminate the whole module?
148  # TODO: it removes it completely from all the data because we do not save/ do not copy it
149 
150  items_time = map(f_time, items)
151  min_value = min(items_time)
152  max_value = max(items_time)
153  max_index = items_time.index(max_value)
154  avg_value = float(sum(items_time)) / float(len(items_time))
155  rms_value = calcRMS(items_time,avg_value)
156 
157  return {"min": min_value, "max": max_value, "cputime_first": cpu_time_first,
158  "rms": rms_value, "avg": avg_value,
159  "event_number_of_max": f_evt_num(items[max_index])}
160 
161 
162 def processModuleTimeLogData(modules_timelog, groupBy = "module_name"):
163  """ Processes the timelog data grouping events by module and calculates min, max, avg, rms
164  Returns data as a list of dicts like: !
165 
166  {
167  <module_name>:
168  {name:, label:,
169  stats: {num_events, avg, min, max, rms}
170  }
171 
172  """
173  # group by module_name, we save a list for each module name
174  times_bymod = {}
175 
176  # print "Num of useful TimeLog lines: %s" % len(modules_timelog)
177 
178  for time_data in modules_timelog:
179  (event_number, module_label, module_name, seconds) = time_data
180 
181  # group times of modules By label or name, TODO: maybe both
182  if groupBy == "module_label":
183  key = module_label
184  else:
185  if groupBy =="name+label":
186  key = module_name + "_" + module_label
187  else:
188  key = module_name
189 
190 
191  try:
192  # is the list for current module initialized?
193  times_bymod[key]
194  except KeyError:
195  #Changing this from a list to a dict (see comments below):
196  #times_bymod[key] = []
197  times_bymod[key] = {}
198  #Running out of memory!
199  #times_bymod[key].append({"label": module_label, "name": module_name, "time": seconds, "event_number": event_number})
200  #Let's do it right:
201  #Instead of times_bymod[key]=[{"label": module_label, "name": module_name, "time": seconds, "event_number": event_number}]
202  #let's do times_bymod[key]={"module_label":{"module_name":[(seconds,event_number)]}} so we do not repeat label and name and especially they are not a pair of key/value
203  #During the first event all the keys will be initialized, then from event 2 on it will be just appending the (seconds,event_number) tuple to the list with the appropriate keys:
204 
205  #Check/Set up the module label dict:
206  try:
207  times_bymod[key][module_label]
208  except KeyError:
209  times_bymod[key].update({module_label:{}})
210 
211  #Check/Set up the module name dict:
212  try:
213  times_bymod[key][module_label][module_name]
214  except KeyError:
215  times_bymod[key][module_label].update({module_name:[]})
216 
217  #We're now ready to add the info as a tuple in the list!
218  times_bymod[key][module_label][module_name].append((seconds,event_number))
219 
220 
221  # calculate Min,Max, Avg, RMS for each module and in this way get the final data to be imported
222  ##for mod_name in times_bymod.keys():
223  ## #copy needed data
224  ## #mod_data = {"label": times_bymod[mod_name][0]["label"], "name": times_bymod[mod_name][0]["name"]}
225  ## #New data structure:
226  ## mod_data = {"label":times_bymod[mod_name].keys()[0],"name":times_bymod[mod_name][times_bymod[mod_name].keys()[0]].keys()[0]}
227  ## # add statistical data
228  ##
229  ## mod_data["stats"] =calc_MinMaxAvgRMS(f_time = lambda x: x["time"], f_evt_num = lambda x: x["event_number"], items = times_bymod[mod_name])
230  ##
231  ## mod_data["stats"]["num_events"] = len(times_bymod[mod_name])
232  ##
233  ## times_bymod[mod_name] = mod_data
234  #Let's rewrite this using the dictionary we now have without any logical change (could do with some...):
235  for key in times_bymod.keys():
236  for label in times_bymod[key].keys():
237  mod_data={'label':label}
238  for name in times_bymod[key][label].keys():
239  mod_data.update({'name':name})
240  mod_data['stats']= calc_MinMaxAvgRMS(f_time= lambda x:x[0],f_evt_num=lambda x:x[1],items=times_bymod[key][label][name])
241  mod_data['stats']['num_events']=len(times_bymod[key][label][name])
242  times_bymod[key]=mod_data
243  return times_bymod
244 
246  timelog_f = "TTBAR__RAW2DIGI,RECO_TimingReport.log"
247  timelog_f = "TTBAR__GEN,SIM,DIGI,L1,DIGI2RAW,HLT_TimingReport.log"
248  #TODO: get STEP name from filename
249  release_files = {
250 
251  "CMSSW_3_1_0_pre9":
252  (
253  "CMSSW_3_1_0_pre9/MINBIAS__RAW2DIGI,RECO_TimingReport.log",
254  "CMSSW_3_1_0_pre9/TTBAR__RAW2DIGI,RECO_TimingReport.log")
255  ## "CMSSW_3_1_0_pre10":
256  }
257  for release, files in release_files.items():
258  print "Processing release: %s" % release
259  for timelog_f in files:
260  print "Processing file: %s" % timelog_f
261 
262  # TODO: automaticaly detect type of report file!!!
263  (mod_timelog, evt_timelog, rss_data, vsize_data) =loadTimeLog(timelog_f)
264 
265  mod_timelog= processModuleTimeLogData(mod_timelog, groupBy = "module_label")
266  print "Number of modules grouped by (module_label): %s" % len(mod_timelog)
267 
268  (candle, step, pileup_type, conditions, event_content) = getJobID_fromTimeReportLogName(timelog_f)
269 
270  """ We could get release from the path but that's quite ugly! """
271  export_xml(jobID = jobID, release=release, timelog_result=(mod_timelog, evt_timelog, rss_data, vsize_data))
272 
273 """ use to run performance profiling """
275  timelog_f = "test_data/TTBAR__RAW2DIGI,RECO_TimingReport.log"
276  (modules_timelog, evt_timelog, rss_data, vsize_data) = loadTimeLog(timelog_f)
277 
278  mod_timelog= processModuleTimeLogData(modules_timelog, groupBy = "module_label")
279 
280  (candle, step, pileup_type, conditions, event_content) = getJobID_fromTimeReportLogName(timelog_f)
281 
282  xmldoc = minidom.Document()
283  export_xml(step = step, candle = candle, release="test", timelog_result=(mod_timelog, evt_timelog, rss_data, vsize_data), xml_doc = xmldoc)
284  write_xml(xmldoc, "test_xml_output.xml")
285 
286 if (__name__ == "__main__"):
287  perf_profile()
def getJobID_fromTimeReportLogName
void strip(std::string &input, const std::string &blanks=" \n\t")
Definition: stringTools.cc:16
def processModuleTimeLogData
mod_data[&quot;stats&quot;] =calc_MinMaxAvgRMS(f_time = lambda x: x[&quot;time&quot;], f_evt_num = lambda x: x[&quot;event_num...
#define min(a, b)
Definition: mlp_lapack.h:161
dictionary map
Definition: Association.py:205
const T & max(const T &a, const T &b)
#define update(a, b)
double split
Definition: MVATrainer.cc:139