-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvisualise.py
201 lines (166 loc) · 6.78 KB
/
visualise.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import random
import sys
def sanitise(string):
'''Sanitises the given string so that it can be output in javascript.
Escaped newlines are handled so that they will be output as newlines
in a string.
Note: This could do a much better job...
'''
return string.replace("<", "\\x3c").replace(">", "\\x3e").replace("\\", "\\\\").replace("'", "\\'").replace('"', '\\x22').replace("\\\\n", "\\n")
class Visualiser(object):
'''This is the main class that does all the work.
'''
# Stuff to tweak
SECS_PER_PX = 0.5 # How many seconds per pixel on the y-axis
ZOOM = 5.0 # A multiplier for all output
# Randomising colours is fine... but choosing the first few from a few stock
# ones helps prevent colours being too close together. Plus it looks better
start_colours = [
'#ff0000',
'#00ff00',
'#0000ff',
'#880000',
'#008800',
'#000088',
'#ff8800',
'#ff00ff',
'#00ffff',
'#000000',
'#888888',
'#88ff00',
'#8800ff',
'#0088ff',
'#00ff88',
]
colours = {} # Map of functions to colours
free_x = [] # points on the x-axis currently unused
max_x = 0 # Maximum width seen so far
stack_traces = {} # Cache of stack traces to reduce size of output
greenlets = {} # Greenlets currently being processed
start_timestamp = None # Earliest timestamp
end_timestamp = 0 # Oldest timestamp
line_num = 0 # Tracks what line number we're at - for error reporting
def next_line(self):
'''Gets the next line in the input.
'''
self.line_num += 1
return sys.stdin.readline().strip()
def go(self):
# Print out necessary headers
print """
<head>
<style>
div {
position: absolute;
border: 1px solid white;
}
</style>
</head>
<script type="text/javascript">
function g(fn, duration, args, stack, left, top, height, width, colour) {
div = document.createElement('div');
div.style.width = width + 'px';
div.style.height = height + 'px';
div.style.top = top + 'px';
div.style.left = left + 'px';
div.style.backgroundColor = colour;
div.onclick = function() {
console.log('Fn: ' + fn + '\\nLength: ' + duration + 's\\nArgs: ' + args +
'\\nStack: ' + stack);
};
document.body.appendChild(div);
}
var stacks = {};
window.onload = function() {
"""
# Process chunks
try:
while self.read_chunk(): pass
except:
sys.stderr.write('Failed at line %d\n' % self.line_num)
raise
# Any greenlets that are left by this stage have not terminated by program end
# Assign a time to them that is twice as long as the time elapsed so far so
# that they stand out
# Their args and function must also be set to blank so they can be output
for greenlet in self.greenlets.values():
greenlet['end'] = self.end_timestamp + (self.end_timestamp - self.start_timestamp)
if 'args' not in greenlet:
greenlet['args'] = ''
if 'fn' not in greenlet:
greenlet['fn'] = ''
self.format_greenlet(greenlet)
print '};</script>'
print '<div style="z-index: 1; position: absolute; right: 100px; top: 0px; width: 150px; height: 100px;">%d concurrent eventlets</div>' % self.max_x
# Print out a horizontal bar across the page to mark where the program ended
print '<div style="z-index: 1; position: absolute; left: 0px; top: %spx; height: 3px; width: %spx; border: 1px solid white; background-color: black"> </div>' % (
self.ZOOM * (self.end_timestamp - self.start_timestamp) / self.SECS_PER_PX,
self.ZOOM * self.max_x * 3,
)
def read_chunk(self):
'''Reads a chunk and stores it in greenlets. If no chunk was found
then returns None. Otherwise, returns the greenlet.
'''
chunk_type = self.next_line()
if chunk_type == '':
return None
_id = self.next_line()
timestamp = float(self.next_line())
if not self.start_timestamp:
self.start_timestamp = timestamp
self.end_timestamp = max(self.end_timestamp, timestamp)
if chunk_type == 'C':
# Chunk indicates the creation of a greenthread
stack = self.next_line()
# free_x tracks the slots on the x-axis that are free
# If no slots are free then we increment the maximum x value
if self.free_x:
x = self.free_x.pop(0)
else:
x = self.max_x
self.max_x += 1
greenlet = {'start': timestamp, 'x': x, 'stack': stack}
self.greenlets[_id] = greenlet
elif chunk_type == 'S':
# Chunk indicates the start of processing of a greenthread
args = self.next_line()
fn, args = args.split(',', 1)
greenlet = self.greenlets[_id]
greenlet['fn'] = fn
greenlet['args'] = args
else:
# Chunk must be the end of a greenthread
greenlet = self.greenlets[_id]
greenlet['end'] = timestamp
del(self.greenlets[_id])
self.free_x.append(greenlet['x'])
self.format_greenlet(greenlet)
return greenlet
def format_greenlet(self, greenlet):
if greenlet['stack'] not in self.stack_traces:
sanitised_stack = sanitise(greenlet['stack'])
print 'stacks[%s] = \'%s\';' % (
len(self.stack_traces),
sanitised_stack
)
self.stack_traces[greenlet['stack']] = len(self.stack_traces)
greenlet['stack'] = self.stack_traces[greenlet['stack']]
# Group greenlets by colour using the function they are calling
if greenlet['fn'] in self.colours:
colour = self.colours[greenlet['fn']]
else:
if self.start_colours:
colour = self.start_colours.pop(0)
else:
colour = '#' + ''.join([random.choice('0123456789ab') for r in range(6)])
self.colours[greenlet['fn']] = colour
fn = sanitise(str(greenlet['fn']))
duration = "%.4f" % (greenlet['end'] - greenlet['start'])
args = sanitise(greenlet['args'])
stack = greenlet['stack']
left = greenlet['x'] * 3 * self.ZOOM
top = "%.1f" % (self.ZOOM * (greenlet['start'] - self.start_timestamp) / self.SECS_PER_PX)
height = self.ZOOM * max(1, (greenlet['end'] - greenlet['start']) / self.SECS_PER_PX) - 2
width = 3 * self.ZOOM - 2
print 'g(\'{fn}\', \'{duration}\', \'{args}\', stacks[{stack}], {left}, {top}, {height}, {width}, \'{colour}\');'.format(**locals())
Visualiser().go()