Class: RubyProf::CallStackPrinter

Inherits:
AbstractPrinter show all
Includes:
ERB::Util
Defined in:
lib/ruby-prof/call_stack_printer.rb

Overview

prints a HTML visualization of the call tree

Instance Method Summary collapse

Methods inherited from AbstractPrinter

#method_name, #min_percent, #print_file, #setup_options

Constructor Details

#initialize(result) ⇒ CallStackPrinter

Returns a new instance of CallStackPrinter.



10
11
12
# File 'lib/ruby-prof/call_stack_printer.rb', line 10

def initialize(result)
  super(result)
end

Instance Method Details

#applicationObject



141
142
143
# File 'lib/ruby-prof/call_stack_printer.rb', line 141

def application
  @options[:application] || $PROGRAM_NAME
end

#argumentsObject



145
146
147
# File 'lib/ruby-prof/call_stack_printer.rb', line 145

def arguments
  ARGV.join(' ')
end

#color(p) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ruby-prof/call_stack_printer.rb', line 128

def color(p)
  case i = p.to_i
  when 0..5
    "01"
  when 5..10
    "05"
  when 100
    "9"
  else
    "#{i/10}"
  end
end

#copy_image_filesObject



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/ruby-prof/call_stack_printer.rb', line 161

def copy_image_files
  if @output.is_a?(File)
    target_dir = File.dirname(@output.path)
    image_dir = File.dirname(__FILE__)
    %w(empty plus minus).each do |img|
      source_file = "#{image_dir}/#{img}.png"
      target_file = "#{target_dir}/#{img}.png"
      FileUtils.cp(source_file, target_file) unless File.exist?(target_file)
    end
  end
end

#dump(ci) ⇒ Object



124
125
126
# File 'lib/ruby-prof/call_stack_printer.rb', line 124

def dump(ci)
  $stderr.printf "%s/%d t:%f s:%f w:%f  \n", ci, ci.object_id, ci.total_time, ci.self_time, ci.wait_time
end

#expansionObject



157
158
159
# File 'lib/ruby-prof/call_stack_printer.rb', line 157

def expansion
  @options[:expansion] || 10.0
end


105
106
107
108
109
110
# File 'lib/ruby-prof/call_stack_printer.rb', line 105

def graph_link(call_info)
  total_calls = call_info.target.call_infos.inject(0){|t, ci| t += ci.called}
  href = "#{@graph_html}##{method_href(call_info.target)}"
  totals = @graph_html ? "<a href='#{href}'>#{total_calls}</a>" : total_calls.to_s
  "[#{call_info.called} calls, #{totals} total]"
end


91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/ruby-prof/call_stack_printer.rb', line 91

def link(call_info)
  method = call_info.target
  file = File.expand_path(method.source_file)
  if file =~ /\/ruby_runtime$/
    h(name(call_info))
  else
    if RUBY_PLATFORM =~ /darwin/
      "<a href=\"txmt://open?url=file://#{file}&line=#{method.line}\">#{h(name(call_info))}</a>"
    else
      "<a href=\"file://#{file}?line=#{method.line}\">#{h(name(call_info))}</a>"
    end
  end
end

#method_href(method) ⇒ Object



112
113
114
# File 'lib/ruby-prof/call_stack_printer.rb', line 112

def method_href(method)
  h(method.full_name.gsub(/[><#\.\?=:]/,"_") + "_" + @current_thread_id.to_s)
end

#name(call_info) ⇒ Object



86
87
88
89
# File 'lib/ruby-prof/call_stack_printer.rb', line 86

def name(call_info)
  method = call_info.target
  method.full_name
end


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
# File 'lib/ruby-prof/call_stack_printer.rb', line 14

def print(output = STDOUT, options = {})
  @output = output
  setup_options(options)
  if @graph_html = options.delete(:graph)
    @graph_html = "file://" + @graph_html if @graph_html[0]=="/"
  end

  @overall_threads_time = 0.0
  @threads_totals = Hash.new
  @result.threads.each do |thread_id, methods|
    roots = methods.select{|m| m.root?}
    thread_total_time = sum(roots.map{|r| self.total_time(r.call_infos)})
    @overall_threads_time += thread_total_time
    @threads_totals[thread_id] = thread_total_time
  end

  print_header

  @result.threads.keys.sort.each do |thread_id|
    @current_thread_id = thread_id
    @overall_time = @threads_totals[thread_id]
    @output.print "<div class=\"thread\">Thread: #{thread_id} (#{"%4.2f%%" % ((@overall_time/@overall_threads_time)*100)} ~ #{@overall_time})</div>"
    @output.print "<ul name=\"thread\">"
    @result.threads[thread_id].each do |m|
      # $stderr.print m.dump
      next unless m.root?
      m.call_infos.each do |ci|
        next unless ci.root?
        print_stack ci, @threads_totals[thread_id]
      end
    end
    @output.print "</ul>"
  end

  print_footer

  copy_image_files
end


719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/ruby-prof/call_stack_printer.rb', line 719

def print_commands
  @output.puts <<-"end_commands"
<div id=\"commands\">
<span style=\"font-size: 11pt; font-weight: bold;\">Threshold:</span>
<input value=\"#{h threshold}\" size=\"3\" id=\"threshold\" type=\"text\">
<input value=\"Apply\" onclick=\"setThreshold();\" type=\"submit\">
<input value=\"Expand All\" onclick=\"expandAll(event);\" type=\"submit\">
<input value=\"Collapse All\" onclick=\"collapseAll(event);\" type=\"submit\">
<input value=\"Show Help\" onclick=\"toggleHelp(this);\" type=\"submit\">
</div>
end_commands
end


189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/ruby-prof/call_stack_printer.rb', line 189

def print_css
  @output.puts <<-'end_css'
<style type="text/css">
<!--
body {
font-size:70%;
padding:0px;
margin:5px;
margin-right:0px;
margin-left:0px;
background: #ffffff;
}
ul {
margin-left:0px;
margin-top:0px;
margin-bottom:0px;
padding-left:0px;
list-style-type:none;
}
li {
margin-left:11px;
padding:0px;
white-space:nowrap;
border-top:1px solid #cccccc;
border-left:1px solid #cccccc;
border-bottom:none;
}
.thread {
margin-left:11px;
background:#708090;
padding-top:3px;
padding-left:12px;
padding-bottom:2px;
border-left:1px solid #CCCCCC;
border-top:1px solid #CCCCCC;
font-weight:bold;
}
.hidden {
display:none;
width:0px;
height:0px;
margin:0px;
padding:0px;
border-style:none;
}
.color01 { background:#adbdeb }
.color05 { background:#9daddb }
.color0 { background:#8d9dcb }
.color1 { background:#89bccb }
.color2 { background:#56e3e7 }
.color3 { background:#32cd70 }
.color4 { background:#a3d53c }
.color5 { background:#c4cb34 }
.color6 { background:#dcb66d }
.color7 { background:#cda59e }
.color8 { background:#be9d9c }
.color9 { background:#cf947a }
#commands {
font-size:10pt;
padding:10px;
margin-left:11px;
margin-bottom:0px;
margin-top:0px;
background:#708090;
border-top:1px solid #cccccc;
border-left:1px solid #cccccc;
border-bottom:none;
}
#titlebar {
font-size:10pt;
padding:10px;
margin-left:11px;
margin-bottom:0px;
margin-top:10px;
background:#8090a0;
border-top:1px solid #cccccc;
border-left:1px solid #cccccc;
border-bottom:none;
}
#help {
font-size:10pt;
padding:10px;
margin-left:11px;
margin-bottom:0px;
margin-top:0px;
background:#8090a0;
display:none;
border-top:1px solid #cccccc;
border-left:1px solid #cccccc;
border-bottom:none;
}
#sentinel {
height: 400px;
margin-left:11px;
background:#8090a0;
border-top:1px solid #cccccc;
border-left:1px solid #cccccc;
border-bottom:none;
 }
input { margin-left:10px; }
-->
</style>
end_css
end


185
186
187
# File 'lib/ruby-prof/call_stack_printer.rb', line 185

def print_footer
  @output.puts '<div id="sentinel"></div></body></html>'
end


173
174
175
176
177
178
179
180
181
182
183
# File 'lib/ruby-prof/call_stack_printer.rb', line 173

def print_header
  @output.puts "<html><head>"
  @output.puts '<meta http-equiv="content-type" content="text/html; charset=utf-8">'
  @output.puts "<title>#{h title}</title>"
  print_css
  print_java_script
  @output.puts '</head><body>'
  print_title_bar
  print_commands
  print_help
end


732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'lib/ruby-prof/call_stack_printer.rb', line 732

def print_help
  @output.puts <<-'end_help'
<div style="display: none;" id="help">
<img src="empty.png"> Enter a decimal value <i>d</i> into the threshold field and click "Apply"
to hide all nodes marked with time values lower than <i>d</i>.<br>
<img src="empty.png"> Click on "Expand All" for full tree expansion.<br>
<img src="empty.png"> Click on "Collapse All" to show only top level nodes.<br>
<img src="empty.png"> Use a, s, d, w as in Quake or Urban Terror to navigate the tree.<br>
<img src="empty.png"> Use f and b to navigate the tree in preorder forward and backwards.<br>
<img src="empty.png"> Use x to toggle visibility of a subtree.<br>
<img src="empty.png"> Use * to expand/collapse a whole subtree.<br>
<img src="empty.png"> Use h to navigate to thread root.<br>
<img src="empty.png"> Use n and p to navigate between threads.<br>
<img src="empty.png"> Click on background to move focus to a subtree.<br>
</div>
end_help
end


294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/ruby-prof/call_stack_printer.rb', line 294

def print_java_script
  @output.puts <<-'end_java_script'
<script type="text/javascript">
/*
   Copyright (C) 2005,2009  Stefan Kaes
   [email protected]
*/

function rootNode() {
  return currentThread;
}

function hideUL(node) {
  var lis = node.childNodes
  var l = lis.length;
  for (var i=0; i < l ; i++ ) {
hideLI(lis[i]);
  }
}

function showUL(node) {
  var lis = node.childNodes;
  var l = lis.length;
  for (var i=0; i < l ; i++ ) {
showLI(lis[i]);
  }
}

function findUlChild(li){
  var ul = li.childNodes[2];
  while (ul && ul.nodeName != "UL") {
ul = ul.nextSibling;
  }
  return ul;
}

function isLeafNode(li) {
  var img = li.firstChild;
  return (img.src.indexOf('empty.png') > -1);
}

function hideLI(li) {
  if (isLeafNode(li))
return;

  var img = li.firstChild;
  img.src = 'plus.png';

  var ul = findUlChild(li);
  if (ul) {
ul.style.display = 'none';
hideUL(ul);
  }
}

function showLI(li) {
  if (isLeafNode(li))
return;

  var img = li.firstChild;
  img.src = 'minus.png';

  var ul = findUlChild(li);
  if (ul) {
ul.style.display = 'block';
showUL(ul);
  }
}

function toggleLI(li) {
  var img = li.firstChild;
  if (img.src.indexOf("minus.png")>-1)
hideLI(li);
  else {
if (img.src.indexOf("plus.png")>-1)
  showLI(li);
  }
}

function aboveThreshold(text, threshold) {
  var match = text.match(/\d+[.,]\d+/);
  return (match && parseFloat(match[0].replace(/,/, '.'))>=threshold);
}

function setThresholdLI(li, threshold) {
  var img = li.firstChild;
  var text = img.nextSibling;
  var ul = findUlChild(li);

  var visible = aboveThreshold(text.nodeValue, threshold) ? 1 : 0;

  var count = 0;
  if (ul) {
count = setThresholdUL(ul, threshold);
  }
  if (count>0) {
img.src = 'minus.png';
  }
  else {
img.src = 'empty.png';
  }
  if (visible) {
li.style.display = 'block'
  }
  else {
li.style.display = 'none'
  }
  return visible;
}

function setThresholdUL(node, threshold) {
  var lis = node.childNodes;
  var l = lis.length;

  var count = 0;
  for ( var i = 0; i < l ; i++ ) {
count = count + setThresholdLI(lis[i], threshold);
  }

  var visible = (count > 0) ? 1 : 0;
  if (visible) {
node.style.display = 'block';
  }
  else {
node.style.display = 'none';
  }
  return visible;
}

function toggleChildren(img, event) {
  event.cancelBubble=true;

  if (img.src.indexOf('empty.png') > -1)
return;

  var minus = (img.src.indexOf('minus.png') > -1);

  if (minus) {
img.src = 'plus.png';
  }
  else
img.src = 'minus.png';

  var li = img.parentNode;
  var ul = findUlChild(li);
  if (ul) {
if (minus)
  ul.style.display = 'none';
else
  ul.style.display = 'block';
  }
  if (minus)
moveSelectionIfNecessary(li);
}

function showChildren(li) {
  var img = li.firstChild;
  if (img.src.indexOf('empty.png') > -1)
return;
  img.src = 'minus.png';

  var ul = findUlChild(li);
  if (ul) {
ul.style.display = 'block';
  }
}

function setThreshold() {
 var tv = document.getElementById("threshold").value;
 if (tv.match(/[0-9]+([.,][0-9]+)?/)) {
   var f = parseFloat(tv.replace(/,/, '.'));
   var threads = document.getElementsByName("thread");
   var l = threads.length;
   for ( var i = 0; i < l ; i++ ) {
 setThresholdUL(threads[i], f);
   }
   var p = selectedNode;
   while (p && p.style.display=='none')
 p=p.parentNode.parentNode;
   if (p && p.nodeName=="LI")
selectNode(p);
 }
 else {
   alert("Please specify a decimal number as threshold value!");
 }
}

function collapseAll(event) {
  event.cancelBubble=true;
  var threads = document.getElementsByName("thread");
  var l = threads.length;
  for ( var i = 0; i < l ; i++ ) {
hideUL(threads[i]);
  }
  selectNode(rootNode(), null);
}

function expandAll(event) {
  event.cancelBubble=true;
  var threads = document.getElementsByName("thread");
  var l = threads.length;
  for ( var i = 0; i < l ; i++ ) {
showUL(threads[i]);
  }
}

function toggleHelp(node) {
  var help = document.getElementById("help");
  if (node.value == "Show Help") {
node.value = "Hide Help";
help.style.display = 'block';
  }
  else {
node.value = "Show Help";
help.style.display = 'none';
  }
}

var selectedNode = null;
var selectedColor = null;
var selectedThread = null;

function descendentOf(a,b){
  while (a!=b && b!=null)
b=b.parentNode;
  return (a==b);
}

function moveSelectionIfNecessary(node){
  if (descendentOf(node, selectedNode))
selectNode(node, null);
}

function selectNode(node, event) {
  if (event) {
event.cancelBubble = true;
thread = findThread(node);
selectThread(thread);
  }
  if (selectedNode) {
selectedNode.style.background = selectedColor;
  }
  selectedNode = node;
  selectedColor = node.style.background;
  selectedNode.style.background = "red";
  selectedNode.scrollIntoView();
  window.scrollBy(0,-400);
}

function moveUp(){
  var p = selectedNode.previousSibling;
  while (p && p.style.display == 'none')
p = p.previousSibling;
  if (p && p.nodeName == "LI") {
selectNode(p, null);
  }
}

function moveDown(){
  var p = selectedNode.nextSibling;
  while (p && p.style.display == 'none')
p = p.nextSibling;
  if (p && p.nodeName == "LI") {
selectNode(p, null);
  }
}

function moveLeft(){
  var p = selectedNode.parentNode.parentNode;
  if (p && p.nodeName=="LI") {
selectNode(p, null);
  }
}

function moveRight(){
  if (!isLeafNode(selectedNode)) {
showChildren(selectedNode);
var ul = findUlChild(selectedNode);
if (ul) {
  selectNode(ul.firstChild, null);
}
  }
}

function moveForward(){
  if (isLeafNode(selectedNode)) {
var p = selectedNode;
while ((p.nextSibling == null || p.nextSibling.style.display=='none') && p.nodeName=="LI") {
  p = p.parentNode.parentNode;
}
if (p.nodeName=="LI")
  selectNode(p.nextSibling, null);
  }
  else {
moveRight();
  }
}

function isExpandedNode(li){
  var img = li.firstChild;
  return(img.src.indexOf('minus.png')>-1);
}

function moveBackward(){
  var p = selectedNode;
  var q = p.previousSibling;
  while (q != null && q.style.display=='none')
q = q.previousSibling;
  if (q == null) {
p = p.parentNode.parentNode;
  } else {
while (!isLeafNode(q) && isExpandedNode(q)) {
  q = findUlChild(q).lastChild;
  while (q.style.display=='none')
    q = q.previousSibling;
}
p = q;
  }
  if (p.nodeName=="LI")
selectNode(p, null);
}

function moveHome() {
  selectNode(currentThread);
}

var currentThreadIndex = null;

function findThread(node){
  while (node && node.parentNode.nodeName!="BODY") {
node = node.parentNode;
  }
  return node.firstChild;
}

function selectThread(node){
  var threads = document.getElementsByName("thread");
  currentThread = node;
  for (var i=0; i<threads.length; i++) {
if (threads[i]==currentThread.parentNode)
  currentThreadIndex = i;
  }
}

function nextThread(){
  var threads = document.getElementsByName("thread");
  if (currentThreadIndex==threads.length-1)
currentThreadIndex = 0;
  else
currentThreadIndex += 1
  currentThread = threads[currentThreadIndex].firstChild;
  selectNode(currentThread, null);
}

function previousThread(){
  var threads = document.getElementsByName("thread");
  if (currentThreadIndex==0)
currentThreadIndex = threads.length-1;
  else
currentThreadIndex -= 1
  currentThread = threads[currentThreadIndex].firstChild;
  selectNode(currentThread, null);
}

function switchThread(node, event){
  event.cancelBubble = true;
  selectThread(node.nextSibling.firstChild);
  selectNode(currentThread, null);
}

function handleKeyEvent(event){
  var code = event.charCode ? event.charCode : event.keyCode;
  var str = String.fromCharCode(code);
  switch (str) {
case "a": moveLeft();  break;
case "s": moveDown();  break;
case "d": moveRight(); break;
case "w": moveUp();    break;
case "f": moveForward(); break;
case "b": moveBackward(); break;
case "x": toggleChildren(selectedNode.firstChild, event); break;
case "*": toggleLI(selectedNode); break;
case "n": nextThread(); break;
case "h": moveHome(); break;
case "p": previousThread(); break;
  }
}
document.onkeypress=function(event){ handleKeyEvent(event) };

window.onload=function(){
  var images = document.getElementsByTagName("img");
  for (var i=0; i<images.length; i++) {
var img = images[i];
if (img.className == "toggle") {
  img.onclick = function(event){ toggleChildren(this, event); };
}
  }
  var divs = document.getElementsByTagName("div");
  for (i=0; i<divs.length; i++) {
var div = divs[i];
if (div.className == "thread")
  div.onclick = function(event){ switchThread(this, event) };
  }
  var lis = document.getElementsByTagName("li");
  for (var i=0; i<lis.length; i++) {
lis[i].onclick = function(event){ selectNode(this, event); };
  }
  var threads = document.getElementsByName("thread");
  currentThreadIndex = 0;
  currentThread = threads[0].firstChild;
  selectNode(currentThread, null);
}
</script>
end_java_script
end


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
# File 'lib/ruby-prof/call_stack_printer.rb', line 53

def print_stack(call_info, parent_time)
  total_time = call_info.total_time
  percent_parent = (total_time/parent_time)*100
  percent_total = (total_time/@overall_time)*100
  return unless percent_total > min_percent
  color = self.color(percent_total)
  kids = call_info.children
  visible = percent_total >= threshold
  expanded = percent_total >= expansion
  display = visible ? "block" : "none"
  @output.print "<li class=\"color#{color}\" style=\"display:#{display}\">"
  if kids.empty?
    @output.print "<img src=\"empty.png\">"
  else
    visible_children = kids.any?{|ci| (ci.total_time/@overall_time)*100 >= threshold}
    image = visible_children ? (expanded ? "minus" : "plus") : "empty"
    @output.print "<img class=\"toggle\" src=\"#{image}.png\">"
  end
  @output.printf " %4.2f%% (%4.2f%%) %s %s\n", percent_total, percent_parent, link(call_info), graph_link(call_info)
  unless kids.empty?
    if expanded
      @output.print "<ul>"
    else
      @output.print '<ul style="display:none">'
    end
    kids.sort_by{|c| -c.total_time}.each do |callinfo|
      print_stack callinfo, total_time
    end
    @output.print "</ul>"
  end
  @output.print "</li>"
end


710
711
712
713
714
715
716
717
# File 'lib/ruby-prof/call_stack_printer.rb', line 710

def print_title_bar
  @output.puts <<-"end_title_bar"
<div id="titlebar">
Call tree for application <b>#{h application} #{h arguments}</b><br/>
Generated on #{Time.now} with options #{h @options.inspect}<br/>
</div>
end_title_bar
end

#sum(a) ⇒ Object



120
121
122
# File 'lib/ruby-prof/call_stack_printer.rb', line 120

def sum(a)
  a.inject(0.0){|s,t| s+=t}
end

#thresholdObject



153
154
155
# File 'lib/ruby-prof/call_stack_printer.rb', line 153

def threshold
  @options[:threshold] || 1.0
end

#titleObject



149
150
151
# File 'lib/ruby-prof/call_stack_printer.rb', line 149

def title
  @title ||= @options.delete(:title) || "ruby-prof call tree"
end

#total_time(call_infos) ⇒ Object



116
117
118
# File 'lib/ruby-prof/call_stack_printer.rb', line 116

def total_time(call_infos)
  sum(call_infos.map{|ci| ci.total_time})
end