Debian Codegraph @

pypy/tool/bench/htmlreport.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import Image
4 import ImageDraw
5 import urllib
6 import StringIO
7 import math
8 import sys
9 import colorsys
10
11 import py
12 pyhtml = py.xml.html
13
14 from result import (
15 PerfResult, PerfResultDelta, PerfResultCollection,
16 PerfTable
17 )
18
19
20 class Page:
21 """generates a benchmark summary page
22 The generated page is self contained, all images are inlined. The
23 page refers to a local css file 'benchmark_report.css'.
24 """
25
26 def __init__(self, perftable=None):
27 """perftable is of type PerfTable"""
28 self.perftable = perftable
29
30 def render(self):
31 """return full rendered page html tree for the perftable."""
32
33 perftable = self.perftable
34 testid2collections = perftable.get_testid2collections()
35
36 # loop to get per-revision collection and the
37 # maximum delta revision collections.
38 maxdeltas = []
39 revdeltas = {}
40 start = end = None
41 for testid, collections in testid2collections.iteritems():
42 if len(collections) < 2: # less than two revisions sampled
43 continue
44 # collections are sorted by lowest REVNO first
45 delta = PerfResultDelta(collections[0], collections[-1])
46 maxdeltas.append(delta)
47
48 # record deltas on target revisions
49 for col1, col2 in zip(collections, collections[1:]):
50 revdelta = PerfResultDelta(col1, col2)
51 l = revdeltas.setdefault(col2.revision, [])
52 l.append(revdelta)
53
54 # keep track of overall earliest and latest revision
55 if start is None or delta._from.revision < start.revision:
56 start = delta._from.results[0]
57 if end is None or delta._to.revision > end.revision:
58 end = delta._to.results[0]
59
60 # sort by best changes first
61 maxdeltas.sort(key=lambda x: x.percent)
62
63 # generate revision reports
64 revno_deltas = revdeltas.items()
65 revno_deltas.sort()
66 revno_deltas.reverse()
67 revreports = []
68 for revno, deltas in revno_deltas:
69 # sort by best changes first
70 deltas.sort(key=lambda x: x.percent)
71 revreports.append(self.render_report(deltas))
72 assert revreports
73
74 # generate images
75 #
76 # generate the x axis, a list of revision numbers
77 xaxis = perftable.list_values_of('revision')
78 xaxis.sort()
79 # samples of tests in the order of max_deltas test_ids
80 samples = [testid2collections[delta.test_id] for delta in maxdeltas]
81 # images in the order of max_deltas test_ids
82 images = [self.gen_image_map(sample, xaxis) for sample in samples]
83
84 page = pyhtml.html(
85 pyhtml.head(
86 pyhtml.meta(
87 name="Content-Type",
88 value="text/html; charset=latin1",
89 ),
90 pyhtml.link(rel="stylesheet",
91 type="text/css",
92 href="benchmark_report.css")
93
94 ),
95 pyhtml.body(
96 #self.render_header(start, end),
97 self.render_table(maxdeltas, images, anchors=False),
98 *revreports
99 )
100 )
101 return page
102
103 def _revision_report_name(self, sample):
104 """return anchor name for reports,
105 used to link from an image to a report"""
106 return 'revno_%s' % (sample.revision,)
107
108 def _revision_test_report_name(self, sample):
109 """return anchor name for reports,
110 used to link from an image to a report"""
111 return 'revno_%s_test_id_%s' % (sample.revision, sample.test_id)
112
113 def gen_image_map(self, samples, revisions=[]):
114 """return a tuple of an inlined image and the corresponding image map
115 samples is a list of PerfResultCollections
116 revisions is a list of revision numbers and represents the x
117 axis of the graph"""
118
119 revision2collection = dict(((s.revision, s) for s in samples))
120 revision2delta = dict()
121 for col1, col2 in zip(samples, samples[1:]):
122 revision2delta[col2.revision] = PerfResultDelta(col1, col2)
123 max_value = max([s.min_elapsed for s in samples])
124 map_name = samples[0].test_id # link between the image and the image map
125 if max_value == 0:
126 #nothing to draw
127 return (pyhtml.span('No value greater than 0'), py.html.span(''))
128
129 step = 3 # pixels for each revision on x axis
130 xsize = (len(revisions) - 1) * step +2
131 ysize = 32 # height of the image
132 im = Image.new("RGB", (xsize + 2, ysize), 'white')
133 draw = ImageDraw.Draw(im)
134
135 areas = []
136 for x, revno in enumerate(revisions):
137 if revno not in revision2collection: # data for this revision?
138 continue
139 sample = revision2collection[revno]
140 y = ysize - (sample.min_elapsed *(ysize -2)/max_value) #scale value
141 #draw.line((x*step, y, (x+1)*step, y), fill="#888888")
142 draw.rectangle((x*step+1, y, x*step + step -1, ysize),
143 fill="#BBBBBB")
144
145 head_color = "#000000"
146 if revno in revision2delta:
147 change = revision2delta[revno].percent
148 if change < -0.15:
149 head_color = "#00FF00"
150 elif change > 0.15:
151 head_color = "#FF0000"
152 draw.rectangle((x*step+1, y-1, x*step + step -1, y+1),
153 fill=head_color)
154
155 areas.append(
156 pyhtml.area(
157 shape="rect",
158 coords= '%s,0,%s,%s' % (x*step, (x+1)*step, ysize),
159 href='#%s' % (self._revision_test_report_name(sample),),
160 title="%s Value: %s" % (sample.revision,sample.min_elapsed)
161 ))
162 del draw
163
164 f = StringIO.StringIO()
165 im.save(f, "GIF")
166 image_src = 'data:image/gif,%s' % (urllib.quote(f.getvalue()),)
167 html_image = pyhtml.img(src=image_src,
168 alt='Benchmark graph of %s' % (self._test_id(
169 sample)),
170 usemap='#%s' % (map_name,))
171 html_map = pyhtml.map(areas, name=map_name)
172 return html_image, html_map
173
174 def _color_for_change(self, delta, max_value=20):
175 """return green for negative change_in_percent and red for
176 positve change_in_percent. If change_in_percent equals 0, then
177 grey is returned.
178
179 The colors range from light green to full saturated green and
180 light red to full saturated red. Full saturation is reached
181 when change_in_percent >= max_value.
182 """
183 #rgb values are between 0 and 255
184 #hsv values are between 0 and 1
185 if len(delta._from) < 3 or len(delta._to) < 3:
186 return '#%02x%02x%02x' % (200,200,200) # grey
187
188 change_in_percent = delta.percent * 100
189 if change_in_percent < 0:
190 basic_color = (0,1,0) # green
191 else:
192 basic_color = (1,0,0) # red
193
194 max_value = 20
195 change = min(abs(change_in_percent), max_value)
196
197 h,s,v = colorsys.rgb_to_hsv(*basic_color)
198 rgb = colorsys.hsv_to_rgb(h, float(change) / max_value, 255)
199 return '#%02x%02x%02x' % rgb
200
201 def _change_report(self, delta):
202 """return a red,green or gray colored html representation of a
203 PerfResultDelta object.
204 """
205
206 fromtimes = [x.elapsed_time for x in delta._from.results]
207 totimes = [x.elapsed_time for x in delta._to.results]
208
209 results = pyhtml.div(
210 "r%d [%s] -> r%d[%s]" %(delta._from.revision,
211 ", ".join(map(str, fromtimes)),
212 delta._to.revision,
213 ", ".join(map(str, totimes)))
214 )
215 return pyhtml.td(
216 pyhtml.div(
217 '%+.1f%% change [%.0f - %.0f = %+.0f ms]' %(
218 delta.percent * 100,
219 delta._to.min_elapsed,
220 delta._from.min_elapsed,
221 delta.delta),
222 style= "background-color: %s" % (
223 self._color_for_change(delta)),
224 ),
225 results,
226 )
227
228 def render_revision_header(self, sample):
229 """return a header for a report with information about
230 committer, messages, revision date.
231 """
232 revision_id = pyhtml.li('Revision ID: %s' % (sample.revision_id,))
233 revision = pyhtml.li('Revision: %s' % (sample.revision,))
234 date = pyhtml.li('Date: %s' % (sample.revision_date,))
235 logmessage = pyhtml.li('Log Message: %s' % (sample.message,))
236 committer = pyhtml.li('Committer: %s' % (sample.committer,))
237 return pyhtml.ul([date, committer, revision, revision_id, logmessage])
238
239 def render_report(self, deltas):
240 """return a report table with header.
241
242 All deltas must have the same revision_id."""
243 deltas = [d for d in deltas if d.test_id]
244
245 sample = deltas[0]._to.getfastest()
246 report_list = self.render_revision_header(sample)
247
248 table = self.render_table(deltas)
249 return pyhtml.div(
250 pyhtml.a(name=self._revision_report_name(sample)),
251 report_list,
252 table,
253 )
254
255 def render_header(self, start, end):
256 """return the header of the page, sample output:
257
258 benchmarks on bzr.dev
259 from r1231 2006-04-01
260 to r1888 2006-07-01
261 """
262 return [
263 pyhtml.div(
264 'Benchmarks for %s' % (start.nick,),
265 class_="titleline maintitle",
266 ),
267 pyhtml.div(
268 'from r%s %s' % (
269 start.revision,
270 start.revision_date,
271 ),
272 class_="titleline",
273 ),
274 pyhtml.div(
275 'to r%s %s' % (
276 end.revision,
277 end.revision_date,
278 ),
279 class_="titleline",
280 ),
281 ]
282
283 def _test_id(self, sample):
284 """helper function, return a short form of a test_id """
285 return '.'.join(sample.test_id.split('.')[-2:])
286
287 def render_table(self, deltas, images=None, anchors=True):
288 """return an html table for deltas and images.
289
290 this function is used to generate the main table and
291 the table of each report"""
292
293 classname = "main"
294 if images is None:
295 classname = "report"
296 images = [None] * len(deltas)
297
298 table = []
299 for delta, image in zip(deltas, images):
300 row = []
301 anchor = ''
302 if anchors:
303 anchor = pyhtml.a(name=self._revision_test_report_name(
304 delta._to.getfastest()))
305 row.append(pyhtml.td(anchor, self._test_id(delta._to.getfastest()),
306 class_='testid'))
307 if image:
308 row.append(pyhtml.td(pyhtml.div(*image)))
309 row.append(self._change_report(delta))
310 table.append(pyhtml.tr(*row))
311 return pyhtml.table(border=1, class_=classname, *table)
312
313
314 def main(path_to_perf_history='../.perf_history'):
315 try:
316 perftable = PerfTable(file(path_to_perf_history).readlines())
317 except IOError:
318 print 'Cannot find a data file. Please specify one.'
319 sys.exit(-1)
320 page = Page(perftable).render()
321 f = file('benchmark_report.html', 'w')
322 try:
323 f.write(page.unicode(indent=2).encode('latin-1'))
324 finally:
325 f.close()
326
327 if __name__ == '__main__':
328 if len(sys.argv) == 1:
329 main()
330 elif len(sys.argv) == 2:
331 main(sys.argv[1])
332 elif len(sys.argv ) == 3:
333 main(*sys.argv[1:3])
334 else:
335 print 'Usage: benchmark_report.py [perf_history [branch]]'
336