Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/gprof2dot.py: 16%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1895 statements  

1#!/usr/bin/env python3 

2# 

3# Copyright 2008-2023 Jose Fonseca 

4# 

5# This program is free software: you can redistribute it and/or modify it 

6# under the terms of the GNU Lesser General Public License as published 

7# by the Free Software Foundation, either version 3 of the License, or 

8# (at your option) any later version. 

9# 

10# This program is distributed in the hope that it will be useful, 

11# but WITHOUT ANY WARRANTY; without even the implied warranty of 

12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

13# GNU Lesser General Public License for more details. 

14# 

15# You should have received a copy of the GNU Lesser General Public License 

16# along with this program. If not, see <http://www.gnu.org/licenses/>. 

17# 

18 

19"""Generate a dot graph from the output of several profilers.""" 

20 

21__author__ = "Jose Fonseca et al" 

22 

23 

24import sys 

25import math 

26import os.path 

27import re 

28import textwrap 

29import argparse 

30import collections 

31import locale 

32import json 

33import fnmatch 

34import codecs 

35import io 

36import hashlib 

37 

38assert sys.version_info >= (3, 10) 

39 

40# Exit status for input this Python can't read (the automake convention for a 

41# skipped test, which the test suite relies on). 

42EXIT_UNSUPPORTED = 77 

43 

44 

45######################################################################## 

46# Model 

47 

48 

49MULTIPLICATION_SIGN = chr(0xd7) 

50DEFAULT_TIME_FORMAT = "%.7g" 

51timeFormat = DEFAULT_TIME_FORMAT 

52 

53 

54def times(x): 

55 return "%u%s" % (x, MULTIPLICATION_SIGN) 

56 

57def percentage(p): 

58 return "%.02f%%" % (p*100.0,) 

59 

60def fmttime(t): 

61 return timeFormat % t 

62 

63def add(a, b): 

64 return a + b 

65 

66def fail(a, b): # pragma: no cover 

67 assert False 

68 

69# To enhance readability, labels are rounded to the number of decimal 

70# places corresponding to the tolerance value. 

71def round_difference(difference, tolerance): 

72 n = -math.floor(math.log10(tolerance)) 

73 return round(difference, n) 

74 

75 

76def rescale_difference(x, min_val, max_val): 

77 return (x - min_val) / (max_val - min_val) 

78 

79 

80def min_max_difference(profile1, profile2): 

81 f1_events = [f1[TOTAL_TIME_RATIO] for _, f1 in sorted_iteritems(profile1.functions)] 

82 f2_events = [f2[TOTAL_TIME_RATIO] for _, f2 in sorted_iteritems(profile2.functions)] 

83 differences = [] 

84 for i in range(len(f1_events)): 

85 try: 

86 differences.append(abs(f1_events[i] - f2_events[i]) * 100) 

87 except IndexError: 

88 differences.append(0) 

89 

90 return min(differences), max(differences) 

91 

92 

93tol = 2 ** -23 

94 

95def ratio(numerator, denominator): 

96 try: 

97 ratio = float(numerator)/float(denominator) 

98 except ZeroDivisionError: 

99 # 0/0 is undefined, but 1.0 yields more useful results 

100 return 1.0 

101 if ratio < 0.0: 

102 if ratio < -tol: # pragma: no cover 

103 sys.stderr.write('warning: negative ratio (%s/%s)\n' % (numerator, denominator)) 

104 return 0.0 

105 if ratio > 1.0: 

106 if ratio > 1.0 + tol: # pragma: no cover 

107 sys.stderr.write('warning: ratio greater than one (%s/%s)\n' % (numerator, denominator)) 

108 return 1.0 

109 return ratio 

110 

111 

112class UndefinedEvent(Exception): 

113 """Raised when attempting to get an event which is undefined.""" 

114 

115 def __init__(self, event): 

116 Exception.__init__(self) 

117 self.event = event 

118 

119 def __str__(self): # pragma: no cover 

120 return 'unspecified event %s' % self.event.name 

121 

122 

123class Event: 

124 """Describe a kind of event, and its basic operations.""" 

125 

126 def __init__(self, name, null, aggregator, formatter = str): 

127 self.name = name 

128 self._null = null 

129 self._aggregator = aggregator 

130 self._formatter = formatter 

131 

132 def __repr__(self): 

133 return self.name 

134 

135 def null(self): 

136 return self._null 

137 

138 def aggregate(self, val1, val2): 

139 """Aggregate two event values.""" 

140 assert val1 is not None 

141 assert val2 is not None 

142 return self._aggregator(val1, val2) 

143 

144 def format(self, val): 

145 """Format an event value.""" 

146 assert val is not None 

147 return self._formatter(val) 

148 

149 

150CALLS = Event("Calls", 0, add, times) 

151SAMPLES = Event("Samples", 0, add, times) 

152SAMPLES2 = Event("Samples", 0, add, times) 

153 

154# Count of samples where a given function was either executing or on the stack. 

155# This is used to calculate the total time ratio according to the 

156# straightforward method described in Mike Dunlavey's answer to 

157# stackoverflow.com/questions/1777556/alternatives-to-gprof, item 4 (the myth 

158# "that recursion is a tricky confusing issue"), last edited 2012-08-30: it's 

159# just the ratio of TOTAL_SAMPLES over the number of samples in the profile. 

160# 

161# Used only when totalMethod == callstacks 

162TOTAL_SAMPLES = Event("Samples", 0, add, times) 

163 

164TIME = Event("Time", 0.0, add, lambda x: '(' + fmttime(x) + ')') 

165TIME_RATIO = Event("Time ratio", 0.0, add, lambda x: '(' + percentage(x) + ')') 

166TOTAL_TIME = Event("Total time", 0.0, fail, fmttime) 

167TOTAL_TIME_RATIO = Event("Total time ratio", 0.0, fail, percentage) 

168 

169labels = { 

170 'self-time': TIME, 

171 'self-time-percentage': TIME_RATIO, 

172 'total-time': TOTAL_TIME, 

173 'total-time-percentage': TOTAL_TIME_RATIO, 

174} 

175defaultLabelNames = ['total-time-percentage', 'self-time-percentage'] 

176 

177DEFAULT_TOTAL_METHOD = 'callratios' 

178totalMethod = DEFAULT_TOTAL_METHOD 

179 

180 

181class Object: 

182 """Base class for all objects in profile which can store events.""" 

183 

184 def __init__(self, events=None): 

185 if events is None: 

186 self.events = {} 

187 else: 

188 self.events = events 

189 

190 def __lt__(self, other): 

191 return id(self) < id(other) 

192 

193 def __contains__(self, event): 

194 return event in self.events 

195 

196 def __getitem__(self, event): 

197 try: 

198 return self.events[event] 

199 except KeyError: 

200 raise UndefinedEvent(event) 

201 

202 def __setitem__(self, event, value): 

203 if value is None: 

204 if event in self.events: 

205 del self.events[event] 

206 else: 

207 self.events[event] = value 

208 

209 

210class Call(Object): 

211 """A call between functions. 

212 

213 There should be at most one call object for every pair of functions. 

214 """ 

215 

216 def __init__(self, callee_id): 

217 Object.__init__(self) 

218 self.callee_id = callee_id 

219 self.ratio = None 

220 self.weight = None 

221 

222 

223class Function(Object): 

224 """A function.""" 

225 

226 def __init__(self, id, name): 

227 Object.__init__(self) 

228 self.id = id 

229 self.name = name 

230 self.module = None 

231 self.process = None 

232 self.calls = {} 

233 self.called = None 

234 self.weight = None 

235 self.cycle = None 

236 self.filename = None 

237 

238 def add_call(self, call): 

239 if call.callee_id in self.calls: # pragma: no cover 

240 sys.stderr.write('warning: overwriting call from function %s to %s\n' % (str(self.id), str(call.callee_id))) 

241 self.calls[call.callee_id] = call 

242 

243 _parenthesis_re = re.compile(r'\([^()]*\)') 

244 _angles_re = re.compile(r'<[^<>]*>') 

245 _const_re = re.compile(r'\s+const$') 

246 

247 def stripped_name(self): 

248 """Remove extraneous information from C++ demangled function names.""" 

249 

250 name = self.name 

251 

252 # Strip function parameters from name by recursively removing paired parenthesis 

253 while True: 

254 name, n = self._parenthesis_re.subn('', name) 

255 if not n: 

256 break 

257 

258 # Strip const qualifier 

259 name = self._const_re.sub('', name) 

260 

261 # Strip template parameters from name by recursively removing paired angles 

262 while True: 

263 name, n = self._angles_re.subn('', name) 

264 if not n: 

265 break 

266 

267 return name 

268 

269 # TODO: write utility functions 

270 

271 def __repr__(self): 

272 return self.name 

273 

274 def dump(self, sep1=",\n\t", sep2=":=", sep3="\n"): 

275 """ Returns as a string all information available in this Function object 

276 separators sep1:between entries 

277 sep2:between attribute name and value, 

278 sep3: inserted at end 

279 """ 

280 return sep1.join(sep2.join([k,str(v)]) for (k,v) in sorted(self.__dict__.items())) + sep3 

281 

282 

283class Cycle(Object): 

284 """A cycle made from recursive function calls.""" 

285 

286 def __init__(self): 

287 Object.__init__(self) 

288 self.functions = set() 

289 

290 def add_function(self, function): 

291 assert function not in self.functions 

292 self.functions.add(function) 

293 if function.cycle is not None: 

294 for other in function.cycle.functions: 

295 if other not in self.functions: 

296 self.add_function(other) 

297 function.cycle = self 

298 

299 

300class Profile(Object): 

301 """The whole profile.""" 

302 

303 def __init__(self): 

304 Object.__init__(self) 

305 self.functions = {} 

306 self.cycles = [] 

307 

308 def add_function(self, function): 

309 if function.id in self.functions: # pragma: no cover 

310 sys.stderr.write('warning: overwriting function %s (id %s)\n' % (function.name, str(function.id))) 

311 self.functions[function.id] = function 

312 

313 def add_cycle(self, cycle): 

314 self.cycles.append(cycle) 

315 

316 def validate(self): 

317 """Validate the edges.""" 

318 

319 for function in self.functions.values(): 

320 for callee_id in list(function.calls.keys()): 

321 assert function.calls[callee_id].callee_id == callee_id 

322 if callee_id not in self.functions: # pragma: no cover 

323 sys.stderr.write('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name)) 

324 del function.calls[callee_id] 

325 

326 def find_cycles(self): 

327 """Find cycles using Tarjan's strongly connected components algorithm.""" 

328 

329 # Apply the Tarjan's algorithm successively until all functions are visited 

330 stack = [] 

331 data = {} 

332 order = 0 

333 for function in self.functions.values(): 

334 order = self._tarjan(function, order, stack, data) 

335 cycles = [] 

336 for function in self.functions.values(): 

337 if function.cycle is not None and function.cycle not in cycles: 

338 cycles.append(function.cycle) 

339 self.cycles = cycles 

340 if 0: 

341 for cycle in cycles: 

342 sys.stderr.write("Cycle:\n") 

343 for member in cycle.functions: 

344 sys.stderr.write("\tFunction %s\n" % member.name) 

345 

346 def prune_root(self, roots, depth=-1): 

347 visited = set() 

348 frontier = set([(root_node, depth) for root_node in roots]) 

349 while len(frontier) > 0: 

350 node, node_depth = frontier.pop() 

351 visited.add(node) 

352 if node_depth == 0: 

353 continue 

354 f = self.functions[node] 

355 newNodes = set(f.calls.keys()) - visited 

356 frontier = frontier.union({(new_node, node_depth - 1) for new_node in newNodes}) 

357 subtreeFunctions = {} 

358 for n in visited: 

359 f = self.functions[n] 

360 newCalls = {} 

361 for c in f.calls.keys(): 

362 if c in visited: 

363 newCalls[c] = f.calls[c] 

364 f.calls = newCalls 

365 subtreeFunctions[n] = f 

366 self.functions = subtreeFunctions 

367 

368 def prune_leaf(self, leafs, depth=-1): 

369 edgesUp = collections.defaultdict(set) 

370 for f in self.functions.keys(): 

371 for n in self.functions[f].calls.keys(): 

372 edgesUp[n].add(f) 

373 # build the tree up 

374 visited = set() 

375 frontier = set([(leaf_node, depth) for leaf_node in leafs]) 

376 while len(frontier) > 0: 

377 node, node_depth = frontier.pop() 

378 visited.add(node) 

379 if node_depth == 0: 

380 continue 

381 newNodes = edgesUp[node] - visited 

382 frontier = frontier.union({(new_node, node_depth - 1) for new_node in newNodes}) 

383 downTree = set(self.functions.keys()) 

384 upTree = visited 

385 path = downTree.intersection(upTree) 

386 pathFunctions = {} 

387 for n in path: 

388 f = self.functions[n] 

389 newCalls = {} 

390 for c in f.calls.keys(): 

391 if c in path: 

392 newCalls[c] = f.calls[c] 

393 f.calls = newCalls 

394 pathFunctions[n] = f 

395 self.functions = pathFunctions 

396 

397 def getFunctionIds(self, funcName): 

398 return [function_id for function_id, function in self.functions.items() 

399 if fnmatch.fnmatch(function.name, funcName)] 

400 

401 def printFunctionIds(self, selector=None, file=None): 

402 """ Print to file function entries selected by fnmatch.fnmatch like in 

403 method getFunctionIds, with following extensions: 

404 - selector starts with "%": dump all information available 

405 - selector is '+' or '-': select all function entries 

406 """ 

407 if file is None: 

408 file = sys.stderr 

409 if selector is None or selector in ("+", "*"): 

410 v = ",\n".join(("%s:\t%s" % (kf,self.functions[kf].name) 

411 for kf in self.functions.keys())) 

412 else: 

413 if selector[0]=="%": 

414 selector=selector[1:] 

415 function_info={k:v for (k,v) 

416 in self.functions.items() 

417 if fnmatch.fnmatch(v.name,selector)} 

418 v = ",\n".join( (f"{v.name}\t({k})\t({type(v)})::\n\t{v.dump()}" 

419 for (k,v) in function_info.items() 

420 )) 

421 

422 else: 

423 function_names = (v.name for v in self.functions.values()) 

424 v = ",\n".join( ( nm for nm in fnmatch.filter(function_names,selector ))) 

425 

426 file.write(v+"\n") 

427 file.flush() 

428 

429 class _TarjanData: 

430 def __init__(self, order): 

431 self.order = order 

432 self.lowlink = order 

433 self.onstack = False 

434 

435 def _tarjan(self, function, order, stack, data): 

436 """Tarjan's strongly connected components algorithm. 

437 

438 See also: 

439 - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm 

440 """ 

441 

442 try: 

443 func_data = data[function.id] 

444 return order 

445 except KeyError: 

446 func_data = self._TarjanData(order) 

447 data[function.id] = func_data 

448 order += 1 

449 pos = len(stack) 

450 stack.append(function) 

451 func_data.onstack = True 

452 for call in function.calls.values(): 

453 try: 

454 callee_data = data[call.callee_id] 

455 if callee_data.onstack: 

456 func_data.lowlink = min(func_data.lowlink, callee_data.order) 

457 except KeyError: 

458 callee = self.functions[call.callee_id] 

459 order = self._tarjan(callee, order, stack, data) 

460 callee_data = data[call.callee_id] 

461 func_data.lowlink = min(func_data.lowlink, callee_data.lowlink) 

462 if func_data.lowlink == func_data.order: 

463 # Strongly connected component found 

464 members = stack[pos:] 

465 del stack[pos:] 

466 if len(members) > 1: 

467 cycle = Cycle() 

468 for member in members: 

469 cycle.add_function(member) 

470 data[member.id].onstack = False 

471 else: 

472 for member in members: 

473 data[member.id].onstack = False 

474 return order 

475 

476 def call_ratios(self, event): 

477 # Aggregate for incoming calls 

478 cycle_totals = {} 

479 for cycle in self.cycles: 

480 cycle_totals[cycle] = 0.0 

481 function_totals = {} 

482 for function in self.functions.values(): 

483 function_totals[function] = 0.0 

484 

485 # Pass 1: function_total gets the sum of call[event] for all 

486 # incoming arrows. Same for cycle_total for all arrows 

487 # that are coming into the *cycle* but are not part of it. 

488 for function in self.functions.values(): 

489 for call in function.calls.values(): 

490 if call.callee_id != function.id: 

491 callee = self.functions[call.callee_id] 

492 if event in call.events: 

493 function_totals[callee] += call[event] 

494 if callee.cycle is not None and callee.cycle is not function.cycle: 

495 cycle_totals[callee.cycle] += call[event] 

496 else: # pragma: no cover 

497 sys.stderr.write("call_ratios: No data for " + function.name + " call to " + callee.name + "\n") 

498 

499 # Pass 2: Compute the ratios. Each call[event] is scaled by the 

500 # function_total of the callee. Calls into cycles use the 

501 # cycle_total, but not calls within cycles. 

502 for function in self.functions.values(): 

503 for call in function.calls.values(): 

504 assert call.ratio is None 

505 if call.callee_id != function.id: 

506 callee = self.functions[call.callee_id] 

507 if event in call.events: 

508 if callee.cycle is not None and callee.cycle is not function.cycle: 

509 total = cycle_totals[callee.cycle] 

510 else: 

511 total = function_totals[callee] 

512 call.ratio = ratio(call[event], total) 

513 else: 

514 # Warnings here would only repeat those issued above. 

515 call.ratio = 0.0 

516 

517 def integrate(self, outevent, inevent): 

518 """Propagate function time ratio along the function calls. 

519 

520 Must be called after finding the cycles. 

521 

522 See also: 

523 - http://citeseer.ist.psu.edu/graham82gprof.html 

524 """ 

525 

526 # Sanity checking 

527 assert outevent not in self 

528 for function in self.functions.values(): 

529 assert outevent not in function 

530 assert inevent in function 

531 for call in function.calls.values(): 

532 assert outevent not in call 

533 if call.callee_id != function.id: 

534 assert call.ratio is not None 

535 

536 # Aggregate the input for each cycle 

537 for cycle in self.cycles: 

538 total = inevent.null() 

539 for function in self.functions.values(): 

540 total = inevent.aggregate(total, function[inevent]) 

541 self[inevent] = total 

542 

543 # Integrate along the edges 

544 total = inevent.null() 

545 for function in self.functions.values(): 

546 total = inevent.aggregate(total, function[inevent]) 

547 self._integrate_function(function, outevent, inevent) 

548 self[outevent] = total 

549 

550 def _integrate_function(self, function, outevent, inevent): 

551 if function.cycle is not None: 

552 return self._integrate_cycle(function.cycle, outevent, inevent) 

553 else: 

554 if outevent not in function: 

555 total = function[inevent] 

556 for call in function.calls.values(): 

557 if call.callee_id != function.id: 

558 total += self._integrate_call(call, outevent, inevent) 

559 function[outevent] = total 

560 return function[outevent] 

561 

562 def _integrate_call(self, call, outevent, inevent): 

563 assert outevent not in call 

564 assert call.ratio is not None 

565 callee = self.functions[call.callee_id] 

566 subtotal = call.ratio *self._integrate_function(callee, outevent, inevent) 

567 call[outevent] = subtotal 

568 return subtotal 

569 

570 def _integrate_cycle(self, cycle, outevent, inevent): 

571 if outevent not in cycle: 

572 

573 # Compute the outevent for the whole cycle 

574 total = inevent.null() 

575 for member in cycle.functions: 

576 subtotal = member[inevent] 

577 for call in member.calls.values(): 

578 callee = self.functions[call.callee_id] 

579 if callee.cycle is not cycle: 

580 subtotal += self._integrate_call(call, outevent, inevent) 

581 total += subtotal 

582 cycle[outevent] = total 

583 

584 # Compute the time propagated to callers of this cycle 

585 callees = {} 

586 for function in self.functions.values(): 

587 if function.cycle is not cycle: 

588 for call in function.calls.values(): 

589 callee = self.functions[call.callee_id] 

590 if callee.cycle is cycle: 

591 try: 

592 callees[callee] += call.ratio 

593 except KeyError: 

594 callees[callee] = call.ratio 

595 

596 for member in cycle.functions: 

597 member[outevent] = outevent.null() 

598 

599 for callee, call_ratio in callees.items(): 

600 ranks = {} 

601 call_ratios = {} 

602 partials = {} 

603 self._rank_cycle_function(cycle, callee, ranks) 

604 self._call_ratios_cycle(cycle, callee, ranks, call_ratios, set()) 

605 partial = self._integrate_cycle_function(cycle, callee, call_ratio, partials, ranks, call_ratios, outevent, inevent) 

606 

607 # Ensure `partial == max(partials.values())`, but with round-off tolerance 

608 max_partial = max(partials.values()) 

609 assert abs(partial - max_partial) <= 1e-7*max_partial 

610 

611 assert abs(call_ratio*total - partial) <= 0.001*call_ratio*total 

612 

613 return cycle[outevent] 

614 

615 def _rank_cycle_function(self, cycle, function, ranks): 

616 """Dijkstra's shortest paths algorithm. 

617 

618 See also: 

619 - http://en.wikipedia.org/wiki/Dijkstra's_algorithm 

620 """ 

621 

622 import heapq 

623 Q = [] 

624 Qd = {} 

625 p = {} 

626 visited = set([function]) 

627 

628 ranks[function] = 0 

629 for call in function.calls.values(): 

630 if call.callee_id != function.id: 

631 callee = self.functions[call.callee_id] 

632 if callee.cycle is cycle: 

633 ranks[callee] = 1 

634 item = [ranks[callee], function, callee] 

635 heapq.heappush(Q, item) 

636 Qd[callee] = item 

637 

638 while Q: 

639 cost, parent, member = heapq.heappop(Q) 

640 if member not in visited: 

641 p[member]= parent 

642 visited.add(member) 

643 for call in member.calls.values(): 

644 if call.callee_id != member.id: 

645 callee = self.functions[call.callee_id] 

646 if callee.cycle is cycle: 

647 member_rank = ranks[member] 

648 rank = ranks.get(callee) 

649 if rank is not None: 

650 if rank > 1 + member_rank: 

651 rank = 1 + member_rank 

652 ranks[callee] = rank 

653 Qd_callee = Qd[callee] 

654 Qd_callee[0] = rank 

655 Qd_callee[1] = member 

656 heapq._siftdown(Q, 0, Q.index(Qd_callee)) 

657 else: 

658 rank = 1 + member_rank 

659 ranks[callee] = rank 

660 item = [rank, member, callee] 

661 heapq.heappush(Q, item) 

662 Qd[callee] = item 

663 

664 def _call_ratios_cycle(self, cycle, function, ranks, call_ratios, visited): 

665 if function not in visited: 

666 visited.add(function) 

667 for call in function.calls.values(): 

668 if call.callee_id != function.id: 

669 callee = self.functions[call.callee_id] 

670 if callee.cycle is cycle: 

671 if ranks[callee] > ranks[function]: 

672 call_ratios[callee] = call_ratios.get(callee, 0.0) + call.ratio 

673 self._call_ratios_cycle(cycle, callee, ranks, call_ratios, visited) 

674 

675 def _integrate_cycle_function(self, cycle, function, partial_ratio, partials, ranks, call_ratios, outevent, inevent): 

676 if function not in partials: 

677 partial = partial_ratio*function[inevent] 

678 for call in function.calls.values(): 

679 if call.callee_id != function.id: 

680 callee = self.functions[call.callee_id] 

681 if callee.cycle is not cycle: 

682 assert outevent in call 

683 partial += partial_ratio*call[outevent] 

684 else: 

685 if ranks[callee] > ranks[function]: 

686 callee_partial = self._integrate_cycle_function(cycle, callee, partial_ratio, partials, ranks, call_ratios, outevent, inevent) 

687 call_ratio = ratio(call.ratio, call_ratios[callee]) 

688 call_partial = call_ratio*callee_partial 

689 try: 

690 call[outevent] += call_partial 

691 except UndefinedEvent: 

692 call[outevent] = call_partial 

693 partial += call_partial 

694 partials[function] = partial 

695 try: 

696 function[outevent] += partial 

697 except UndefinedEvent: 

698 function[outevent] = partial 

699 return partials[function] 

700 

701 def aggregate(self, event): 

702 """Aggregate an event for the whole profile.""" 

703 

704 total = event.null() 

705 for function in self.functions.values(): 

706 try: 

707 total = event.aggregate(total, function[event]) 

708 except UndefinedEvent: 

709 return 

710 self[event] = total 

711 

712 def ratio(self, outevent, inevent): 

713 assert outevent not in self 

714 assert inevent in self 

715 for function in self.functions.values(): 

716 assert outevent not in function 

717 assert inevent in function 

718 function[outevent] = ratio(function[inevent], self[inevent]) 

719 for call in function.calls.values(): 

720 assert outevent not in call 

721 if inevent in call: 

722 call[outevent] = ratio(call[inevent], self[inevent]) 

723 self[outevent] = 1.0 

724 

725 def prune(self, node_thres, edge_thres, paths, color_nodes_by_selftime): 

726 """Prune the profile""" 

727 

728 # compute the prune ratios 

729 for function in self.functions.values(): 

730 try: 

731 function.weight = function[TOTAL_TIME_RATIO] 

732 except UndefinedEvent: 

733 pass 

734 

735 for call in function.calls.values(): 

736 callee = self.functions[call.callee_id] 

737 

738 if TOTAL_TIME_RATIO in call: 

739 # handle exact cases first 

740 call.weight = call[TOTAL_TIME_RATIO] 

741 else: 

742 try: 

743 # make a safe estimate 

744 call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO]) 

745 except UndefinedEvent: 

746 pass 

747 

748 # prune the nodes 

749 for function_id in list(self.functions.keys()): 

750 function = self.functions[function_id] 

751 if function.weight is not None: 

752 if function.weight < node_thres: 

753 del self.functions[function_id] 

754 

755 # prune file paths 

756 for function_id in list(self.functions.keys()): 

757 function = self.functions[function_id] 

758 if paths and function.filename and not any(function.filename.startswith(path) for path in paths): 

759 del self.functions[function_id] 

760 elif paths and function.module and not any((function.module.find(path)>-1) for path in paths): 

761 del self.functions[function_id] 

762 

763 # prune the edges 

764 for function in self.functions.values(): 

765 for callee_id in list(function.calls.keys()): 

766 call = function.calls[callee_id] 

767 if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres: 

768 del function.calls[callee_id] 

769 

770 if color_nodes_by_selftime: 

771 weights = [] 

772 for function in self.functions.values(): 

773 try: 

774 weights.append(function[TIME_RATIO]) 

775 except UndefinedEvent: 

776 pass 

777 max_ratio = max(weights or [1]) 

778 

779 # apply rescaled weights for coloriung 

780 for function in self.functions.values(): 

781 try: 

782 function.weight = function[TIME_RATIO] / max_ratio 

783 except (ZeroDivisionError, UndefinedEvent): 

784 pass 

785 

786 def dump(self): 

787 for function in self.functions.values(): 

788 sys.stderr.write('Function %s:\n' % (function.name,)) 

789 self._dump_events(function.events) 

790 for call in function.calls.values(): 

791 callee = self.functions[call.callee_id] 

792 sys.stderr.write(' Call %s:\n' % (callee.name,)) 

793 self._dump_events(call.events) 

794 for cycle in self.cycles: 

795 sys.stderr.write('Cycle:\n') 

796 self._dump_events(cycle.events) 

797 for function in cycle.functions: 

798 sys.stderr.write(' Function %s\n' % (function.name,)) 

799 

800 def _dump_events(self, events): 

801 for event, value in events.items(): 

802 sys.stderr.write(' %s: %s\n' % (event.name, event.format(value))) 

803 

804 

805 

806######################################################################## 

807# Parsers 

808 

809 

810class Struct: 

811 """Masquerade a dictionary with a structure-like behavior.""" 

812 

813 def __init__(self, attrs = None): 

814 if attrs is None: 

815 attrs = {} 

816 self.__dict__['_attrs'] = attrs 

817 

818 def __getattr__(self, name): 

819 try: 

820 return self._attrs[name] 

821 except KeyError: # pragma: no cover 

822 raise AttributeError(name) 

823 

824 def __setattr__(self, name, value): 

825 self._attrs[name] = value 

826 

827 def __str__(self): 

828 return str(self._attrs) 

829 

830 def __repr__(self): 

831 return repr(self._attrs) 

832 

833 

834class ParseError(Exception): # pragma: no cover 

835 """Raised when parsing to signal mismatches.""" 

836 

837 def __init__(self, msg, line): 

838 Exception.__init__(self) 

839 self.msg = msg 

840 # TODO: store more source line information 

841 self.line = line 

842 

843 def __str__(self): 

844 return '%s: %r' % (self.msg, self.line) 

845 

846 

847class Parser: 

848 """Parser interface.""" 

849 

850 stdinInput = True 

851 multipleInput = False 

852 

853 def __init__(self): 

854 pass 

855 

856 def parse(self): # pragma: no cover 

857 raise NotImplementedError 

858 

859 

860class JsonParser(Parser): 

861 """Parser for a custom JSON representation of profile data. 

862 

863 See schema.json for details. 

864 """ 

865 

866 

867 def __init__(self, stream): 

868 Parser.__init__(self) 

869 self.stream = stream 

870 

871 @staticmethod 

872 def _reject_constant(token): # pragma: no cover 

873 # NaN/Infinity are not valid JSON (schema.json defines costs as finite 

874 # numbers), but Python's json module accepts them as an extension. A 

875 # non-finite cost poisons the SAMPLES total and every derived ratio, so 

876 # refuse the tokens instead of accepting them. 

877 raise ValueError('invalid JSON token %r' % token) 

878 

879 def parse(self): 

880 

881 try: 

882 obj = json.load(self.stream, parse_constant=self._reject_constant) 

883 except ValueError as ex: # pragma: no cover 

884 sys.stderr.write('error: %s\n' % ex) 

885 sys.exit(1) 

886 

887 assert obj['version'] == 0 

888 

889 profile = Profile() 

890 profile[SAMPLES] = 0 

891 

892 fns = obj['functions'] 

893 

894 for functionIndex in range(len(fns)): 

895 fn = fns[functionIndex] 

896 function = Function(functionIndex, fn['name']) 

897 try: 

898 function.module = fn['module'] 

899 except KeyError: 

900 pass 

901 try: 

902 function.process = fn['process'] 

903 except KeyError: 

904 pass 

905 function[SAMPLES] = 0 

906 function.called = 0 

907 profile.add_function(function) 

908 

909 for event in obj['events']: 

910 callchain = [] 

911 

912 for functionIndex in event['callchain']: 

913 function = profile.functions[functionIndex] 

914 callchain.append(function) 

915 

916 # increment the call count of the first in the callchain 

917 function = profile.functions[event['callchain'][0]] 

918 function.called = function.called + 1 

919 

920 cost = event['cost'][0] 

921 

922 callee = callchain[0] 

923 callee[SAMPLES] += cost 

924 profile[SAMPLES] += cost 

925 

926 for caller in callchain[1:]: 

927 try: 

928 call = caller.calls[callee.id] 

929 except KeyError: 

930 call = Call(callee.id) 

931 call[SAMPLES2] = cost 

932 caller.add_call(call) 

933 else: 

934 call[SAMPLES2] += cost 

935 

936 callee = caller 

937 

938 if False: 

939 profile.dump() 

940 

941 # compute derived data 

942 profile.validate() 

943 profile.find_cycles() 

944 profile.ratio(TIME_RATIO, SAMPLES) 

945 profile.call_ratios(SAMPLES2) 

946 profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

947 

948 return profile 

949 

950 

951class LineParser(Parser): 

952 """Base class for parsers that read line-based formats.""" 

953 

954 def __init__(self, stream): 

955 Parser.__init__(self) 

956 self._stream = stream 

957 self.__line = None 

958 self.__eof = False 

959 self.line_no = 0 

960 

961 def readline(self): 

962 line = self._stream.readline() 

963 if not line: 

964 self.__line = '' 

965 self.__eof = True 

966 else: 

967 self.line_no += 1 

968 line = line.rstrip('\r\n') 

969 self.__line = line 

970 

971 def lookahead(self): 

972 assert self.__line is not None 

973 return self.__line 

974 

975 def consume(self): 

976 assert self.__line is not None 

977 line = self.__line 

978 self.readline() 

979 return line 

980 

981 def eof(self): 

982 assert self.__line is not None 

983 return self.__eof 

984 

985 

986class GprofParser(Parser): 

987 """Parser for GNU gprof output. 

988 

989 See also: 

990 - Chapter "Interpreting gprof's Output" from the GNU gprof manual 

991 http://sourceware.org/binutils/docs-2.18/gprof/Call-Graph.html#Call-Graph 

992 - File "cg_print.c" from the GNU gprof source code 

993 http://sourceware.org/cgi-bin/cvsweb.cgi/~checkout~/src/gprof/cg_print.c?rev=1.12&cvsroot=src 

994 """ 

995 

996 def __init__(self, fp): 

997 Parser.__init__(self) 

998 self.fp = fp 

999 self.functions = {} 

1000 self.cycles = {} 

1001 

1002 def readline(self): 

1003 line = self.fp.readline() 

1004 if not line: # pragma: no cover 

1005 sys.stderr.write('error: unexpected end of file\n') 

1006 sys.exit(1) 

1007 line = line.rstrip('\r\n') 

1008 return line 

1009 

1010 _int_re = re.compile(r'^\d+$') 

1011 _float_re = re.compile(r'^\d+\.\d+$') 

1012 

1013 def translate(self, mo): 

1014 """Extract a structure from a match object, while translating the types in the process.""" 

1015 attrs = {} 

1016 groupdict = mo.groupdict() 

1017 for name, value in groupdict.items(): 

1018 if value is None: 

1019 value = None 

1020 elif self._int_re.match(value): 

1021 value = int(value) 

1022 elif self._float_re.match(value): 

1023 value = float(value) 

1024 attrs[name] = (value) 

1025 return Struct(attrs) 

1026 

1027 _cg_header_re = re.compile( 

1028 # original gprof header 

1029 r'^\s+called/total\s+parents\s*$|' + 

1030 r'^index\s+%time\s+self\s+descendents\s+called\+self\s+name\s+index\s*$|' + 

1031 r'^\s+called/total\s+children\s*$|' + 

1032 # GNU gprof header 

1033 r'^index\s+%\s+(time\s+)?self\s+children\s+called\s+name\s*$' 

1034 ) 

1035 

1036 _cg_ignore_re = re.compile( 

1037 # spontaneous 

1038 r'^\s+<spontaneous>\s*$|' 

1039 # internal calls (such as "mcount") 

1040 r'^.*\((\d+)\)$' 

1041 ) 

1042 

1043 _cg_primary_re = re.compile( 

1044 r'^\[(?P<index>\d+)\]?' + 

1045 r'\s+(?P<percentage_time>\d+\.\d+)' + 

1046 r'\s+(?P<self>\d+\.\d+)' + 

1047 r'\s+(?P<descendants>\d+\.\d+)' + 

1048 r'\s+(?:(?P<called>\d+)(?:\+(?P<called_self>\d+))?)?' + 

1049 r'\s+(?P<name>\S.*?)' + 

1050 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1051 r'\s\[(\d+)\]$' 

1052 ) 

1053 

1054 _cg_parent_re = re.compile( 

1055 r'^\s+(?P<self>\d+\.\d+)?' + 

1056 r'\s+(?P<descendants>\d+\.\d+)?' + 

1057 r'\s+(?P<called>\d+)(?:/(?P<called_total>\d+))?' + 

1058 r'\s+(?P<name>\S.*?)' + 

1059 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1060 r'\s\[(?P<index>\d+)\]$' 

1061 ) 

1062 

1063 _cg_child_re = _cg_parent_re 

1064 

1065 _cg_cycle_header_re = re.compile( 

1066 r'^\[(?P<index>\d+)\]?' + 

1067 r'\s+(?P<percentage_time>\d+\.\d+)' + 

1068 r'\s+(?P<self>\d+\.\d+)' + 

1069 r'\s+(?P<descendants>\d+\.\d+)' + 

1070 r'\s+(?:(?P<called>\d+)(?:\+(?P<called_self>\d+))?)?' + 

1071 r'\s+<cycle\s(?P<cycle>\d+)\sas\sa\swhole>' + 

1072 r'\s\[(\d+)\]$' 

1073 ) 

1074 

1075 _cg_cycle_member_re = re.compile( 

1076 r'^\s+(?P<self>\d+\.\d+)?' + 

1077 r'\s+(?P<descendants>\d+\.\d+)?' + 

1078 r'\s+(?P<called>\d+)(?:\+(?P<called_self>\d+))?' + 

1079 r'\s+(?P<name>\S.*?)' + 

1080 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1081 r'\s\[(?P<index>\d+)\]$' 

1082 ) 

1083 

1084 _cg_sep_re = re.compile(r'^--+$') 

1085 

1086 def parse_function_entry(self, lines): 

1087 parents = [] 

1088 children = [] 

1089 

1090 while True: 

1091 if not lines: # pragma: no cover 

1092 sys.stderr.write('warning: unexpected end of entry\n') 

1093 line = lines.pop(0) 

1094 if line.startswith('['): 

1095 break 

1096 

1097 # read function parent line 

1098 mo = self._cg_parent_re.match(line) 

1099 if not mo: 

1100 if self._cg_ignore_re.match(line): 

1101 continue 

1102 sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) 

1103 else: 

1104 parent = self.translate(mo) 

1105 parents.append(parent) 

1106 

1107 # read primary line 

1108 mo = self._cg_primary_re.match(line) 

1109 if not mo: # pragma: no cover 

1110 sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) 

1111 return 

1112 else: 

1113 function = self.translate(mo) 

1114 

1115 while lines: 

1116 line = lines.pop(0) 

1117 

1118 # read function subroutine line 

1119 mo = self._cg_child_re.match(line) 

1120 if not mo: 

1121 if self._cg_ignore_re.match(line): 

1122 continue 

1123 sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) # pragma: no cover 

1124 else: 

1125 child = self.translate(mo) 

1126 children.append(child) 

1127 

1128 function.parents = parents 

1129 function.children = children 

1130 

1131 self.functions[function.index] = function 

1132 

1133 def parse_cycle_entry(self, lines): 

1134 

1135 # read cycle header line 

1136 line = lines[0] 

1137 mo = self._cg_cycle_header_re.match(line) 

1138 if not mo: # pragma: no cover 

1139 sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) 

1140 return 

1141 cycle = self.translate(mo) 

1142 

1143 # read cycle member lines 

1144 cycle.functions = [] 

1145 for line in lines[1:]: 

1146 mo = self._cg_cycle_member_re.match(line) 

1147 if not mo: # pragma: no cover 

1148 sys.stderr.write('warning: unrecognized call graph entry: %r\n' % line) 

1149 continue 

1150 call = self.translate(mo) 

1151 cycle.functions.append(call) 

1152 

1153 self.cycles[cycle.cycle] = cycle 

1154 

1155 def parse_cg_entry(self, lines): 

1156 if lines[0].startswith("["): 

1157 self.parse_cycle_entry(lines) 

1158 else: 

1159 self.parse_function_entry(lines) 

1160 

1161 def parse_cg(self): 

1162 """Parse the call graph.""" 

1163 

1164 # skip call graph header 

1165 while not self._cg_header_re.match(self.readline()): 

1166 pass 

1167 line = self.readline() 

1168 while self._cg_header_re.match(line): 

1169 line = self.readline() 

1170 

1171 # process call graph entries 

1172 entry_lines = [] 

1173 while line != '\014': # form feed 

1174 if line and not line.isspace(): 

1175 if self._cg_sep_re.match(line): 

1176 self.parse_cg_entry(entry_lines) 

1177 entry_lines = [] 

1178 else: 

1179 entry_lines.append(line) 

1180 line = self.readline() 

1181 

1182 def parse(self): 

1183 self.parse_cg() 

1184 self.fp.close() 

1185 

1186 profile = Profile() 

1187 profile[TIME] = 0.0 

1188 

1189 cycles = {} 

1190 for index in self.cycles: 

1191 cycles[index] = Cycle() 

1192 

1193 for entry in self.functions.values(): 

1194 # populate the function 

1195 function = Function(entry.index, entry.name) 

1196 function[TIME] = entry.self 

1197 if entry.called is not None: 

1198 function.called = entry.called 

1199 if entry.called_self is not None: 

1200 call = Call(entry.index) 

1201 call[CALLS] = entry.called_self 

1202 function.called += entry.called_self 

1203 

1204 # populate the function calls 

1205 for child in entry.children: 

1206 call = Call(child.index) 

1207 

1208 assert child.called is not None 

1209 call[CALLS] = child.called 

1210 

1211 if child.index not in self.functions: 

1212 # NOTE: functions that were never called but were discovered by gprof's 

1213 # static call graph analysis dont have a call graph entry so we need 

1214 # to add them here 

1215 missing = Function(child.index, child.name) 

1216 missing[TIME] = 0.0 

1217 missing.called = 0 

1218 profile.add_function(missing) 

1219 

1220 function.add_call(call) 

1221 

1222 profile.add_function(function) 

1223 

1224 if entry.cycle is not None: 

1225 try: 

1226 cycle = cycles[entry.cycle] 

1227 except KeyError: 

1228 sys.stderr.write('warning: <cycle %u as a whole> entry missing\n' % entry.cycle) 

1229 cycle = Cycle() 

1230 cycles[entry.cycle] = cycle 

1231 cycle.add_function(function) 

1232 

1233 profile[TIME] = profile[TIME] + function[TIME] 

1234 

1235 for cycle in cycles.values(): 

1236 profile.add_cycle(cycle) 

1237 

1238 # Compute derived events 

1239 profile.validate() 

1240 profile.ratio(TIME_RATIO, TIME) 

1241 profile.call_ratios(CALLS) 

1242 profile.integrate(TOTAL_TIME, TIME) 

1243 profile.ratio(TOTAL_TIME_RATIO, TOTAL_TIME) 

1244 

1245 return profile 

1246 

1247 

1248# Clone&hack of GprofParser for VTune Amplifier XE 2013 gprof-cc output. 

1249# Tested only with AXE 2013 for Windows. 

1250# - Use total times as reported by AXE. 

1251# - In the absence of call counts, call ratios are faked from the relative 

1252# proportions of total time. This affects only the weighting of the calls. 

1253# - Different header, separator, and end marker. 

1254# - Extra whitespace after function names. 

1255# - You get a full entry for <spontaneous>, which does not have parents. 

1256# - Cycles do have parents. These are saved but unused (as they are 

1257# for functions). 

1258# - Disambiguated "unrecognized call graph entry" error messages. 

1259# Notes: 

1260# - Total time of functions as reported by AXE passes the val3 test. 

1261# - CPU Time:Children in the input is sometimes a negative number. This 

1262# value goes to the variable descendants, which is unused. 

1263# - The format of gprof-cc reports is unaffected by the use of 

1264# -knob enable-call-counts=true (no call counts, ever), or 

1265# -show-as=samples (results are quoted in seconds regardless). 

1266class AXEParser(Parser): 

1267 "Parser for Intel VTune gprof-cc report output (`vtune -report gprof-cc`)." 

1268 

1269 def __init__(self, fp): 

1270 Parser.__init__(self) 

1271 self.fp = fp 

1272 self.functions = {} 

1273 self.cycles = {} 

1274 

1275 def readline(self): 

1276 line = self.fp.readline() 

1277 if not line: # pragma: no cover 

1278 sys.stderr.write('error: unexpected end of file\n') 

1279 sys.exit(1) 

1280 line = line.rstrip('\r\n') 

1281 return line 

1282 

1283 _int_re = re.compile(r'^\d+$') 

1284 _float_re = re.compile(r'^\d+\.\d+$') 

1285 

1286 def translate(self, mo): 

1287 """Extract a structure from a match object, while translating the types in the process.""" 

1288 attrs = {} 

1289 groupdict = mo.groupdict() 

1290 for name, value in groupdict.items(): 

1291 if value is None: 

1292 value = None 

1293 elif self._int_re.match(value): 

1294 value = int(value) 

1295 elif self._float_re.match(value): 

1296 value = float(value) 

1297 attrs[name] = (value) 

1298 return Struct(attrs) 

1299 

1300 _cg_header_re = re.compile( 

1301 '^Index |' 

1302 '^-----+ ' 

1303 ) 

1304 

1305 _cg_footer_re = re.compile(r'^Index\s+Function\s*$') 

1306 

1307 _cg_primary_re = re.compile( 

1308 r'^\[(?P<index>\d+)\]?' + 

1309 r'\s+(?P<percentage_time>\d+\.\d+)' + 

1310 r'\s+(?P<self>\d+\.\d+)' + 

1311 r'\s+(?P<descendants>\d+\.\d+)' + 

1312 r'\s+(?P<name>\S.*?)' + 

1313 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1314 r'\s+\[(\d+)\]' + 

1315 r'\s*$' 

1316 ) 

1317 

1318 _cg_parent_re = re.compile( 

1319 r'^\s+(?P<self>\d+\.\d+)?' + 

1320 r'\s+(?P<descendants>\d+\.\d+)?' + 

1321 r'\s+(?P<name>\S.*?)' + 

1322 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1323 r'(?:\s+\[(?P<index>\d+)\]\s*)?' + 

1324 r'\s*$' 

1325 ) 

1326 

1327 _cg_child_re = _cg_parent_re 

1328 

1329 _cg_cycle_header_re = re.compile( 

1330 r'^\[(?P<index>\d+)\]?' + 

1331 r'\s+(?P<percentage_time>\d+\.\d+)' + 

1332 r'\s+(?P<self>\d+\.\d+)' + 

1333 r'\s+(?P<descendants>\d+\.\d+)' + 

1334 r'\s+<cycle\s(?P<cycle>\d+)\sas\sa\swhole>' + 

1335 r'\s+\[(\d+)\]' + 

1336 r'\s*$' 

1337 ) 

1338 

1339 _cg_cycle_member_re = re.compile( 

1340 r'^\s+(?P<self>\d+\.\d+)?' + 

1341 r'\s+(?P<descendants>\d+\.\d+)?' + 

1342 r'\s+(?P<name>\S.*?)' + 

1343 r'(?:\s+<cycle\s(?P<cycle>\d+)>)?' + 

1344 r'\s+\[(?P<index>\d+)\]' + 

1345 r'\s*$' 

1346 ) 

1347 

1348 def parse_function_entry(self, lines): 

1349 parents = [] 

1350 children = [] 

1351 

1352 while True: 

1353 if not lines: # pragma: no cover 

1354 sys.stderr.write('warning: unexpected end of entry\n') 

1355 return 

1356 line = lines.pop(0) 

1357 if line.startswith('['): 

1358 break 

1359 

1360 # read function parent line 

1361 mo = self._cg_parent_re.match(line) 

1362 if not mo: # pragma: no cover 

1363 sys.stderr.write('warning: unrecognized call graph entry (1): %r\n' % line) 

1364 else: 

1365 parent = self.translate(mo) 

1366 if parent.name != '<spontaneous>': 

1367 parents.append(parent) 

1368 

1369 # read primary line 

1370 mo = self._cg_primary_re.match(line) 

1371 if not mo: # pragma: no cover 

1372 sys.stderr.write('warning: unrecognized call graph entry (2): %r\n' % line) 

1373 return 

1374 else: 

1375 function = self.translate(mo) 

1376 

1377 while lines: 

1378 line = lines.pop(0) 

1379 

1380 # read function subroutine line 

1381 mo = self._cg_child_re.match(line) 

1382 if not mo: # pragma: no cover 

1383 sys.stderr.write('warning: unrecognized call graph entry (3): %r\n' % line) 

1384 else: 

1385 child = self.translate(mo) 

1386 if child.name != '<spontaneous>': 

1387 children.append(child) 

1388 

1389 if function.name != '<spontaneous>': 

1390 function.parents = parents 

1391 function.children = children 

1392 

1393 self.functions[function.index] = function 

1394 

1395 def parse_cycle_entry(self, lines): 

1396 

1397 # Process the parents that were not there in gprof format. 

1398 parents = [] 

1399 while True: 

1400 if not lines: # pragma: no cover 

1401 sys.stderr.write('warning: unexpected end of cycle entry\n') 

1402 return 

1403 line = lines.pop(0) 

1404 if line.startswith('['): 

1405 break 

1406 mo = self._cg_parent_re.match(line) 

1407 if not mo: # pragma: no cover 

1408 sys.stderr.write('warning: unrecognized call graph entry (6): %r\n' % line) 

1409 else: 

1410 parent = self.translate(mo) 

1411 if parent.name != '<spontaneous>': 

1412 parents.append(parent) 

1413 

1414 # read cycle header line 

1415 mo = self._cg_cycle_header_re.match(line) 

1416 if not mo: # pragma: no cover 

1417 sys.stderr.write('warning: unrecognized call graph entry (4): %r\n' % line) 

1418 return 

1419 cycle = self.translate(mo) 

1420 

1421 # read cycle member lines 

1422 cycle.functions = [] 

1423 for line in lines[1:]: 

1424 mo = self._cg_cycle_member_re.match(line) 

1425 if not mo: # pragma: no cover 

1426 sys.stderr.write('warning: unrecognized call graph entry (5): %r\n' % line) 

1427 continue 

1428 call = self.translate(mo) 

1429 cycle.functions.append(call) 

1430 

1431 cycle.parents = parents 

1432 self.cycles[cycle.cycle] = cycle 

1433 

1434 def parse_cg_entry(self, lines): 

1435 if any("as a whole" in linelooper for linelooper in lines): 

1436 self.parse_cycle_entry(lines) 

1437 else: 

1438 self.parse_function_entry(lines) 

1439 

1440 def parse_cg(self): 

1441 """Parse the call graph.""" 

1442 

1443 # skip call graph header 

1444 line = self.readline() 

1445 while self._cg_header_re.match(line): 

1446 line = self.readline() 

1447 

1448 # process call graph entries 

1449 entry_lines = [] 

1450 # An EOF in readline terminates the program without returning. 

1451 while not self._cg_footer_re.match(line): 

1452 if line.isspace(): 

1453 self.parse_cg_entry(entry_lines) 

1454 entry_lines = [] 

1455 else: 

1456 entry_lines.append(line) 

1457 line = self.readline() 

1458 

1459 def parse(self): 

1460 sys.stderr.write('warning: for axe format, edge weights are unreliable estimates derived from function total times.\n') 

1461 self.parse_cg() 

1462 self.fp.close() 

1463 

1464 profile = Profile() 

1465 profile[TIME] = 0.0 

1466 

1467 cycles = {} 

1468 for index in self.cycles: 

1469 cycles[index] = Cycle() 

1470 

1471 for entry in self.functions.values(): 

1472 # populate the function 

1473 function = Function(entry.index, entry.name) 

1474 function[TIME] = entry.self 

1475 function[TOTAL_TIME_RATIO] = entry.percentage_time / 100.0 

1476 

1477 # populate the function calls 

1478 for child in entry.children: 

1479 call = Call(child.index) 

1480 # The following bogus value affects only the weighting of 

1481 # the calls. 

1482 call[TOTAL_TIME_RATIO] = function[TOTAL_TIME_RATIO] 

1483 

1484 if child.index not in self.functions: 

1485 # NOTE: functions that were never called but were discovered by gprof's 

1486 # static call graph analysis dont have a call graph entry so we need 

1487 # to add them here 

1488 # FIXME: Is this applicable? 

1489 missing = Function(child.index, child.name) 

1490 missing[TIME] = 0.0 

1491 missing[TOTAL_TIME_RATIO] = 0.0 

1492 profile.add_function(missing) 

1493 

1494 function.add_call(call) 

1495 

1496 profile.add_function(function) 

1497 

1498 if entry.cycle is not None: 

1499 try: 

1500 cycle = cycles[entry.cycle] 

1501 except KeyError: # pragma: no cover 

1502 sys.stderr.write('warning: <cycle %u as a whole> entry missing\n' % entry.cycle) 

1503 cycle = Cycle() 

1504 cycles[entry.cycle] = cycle 

1505 cycle.add_function(function) 

1506 

1507 profile[TIME] = profile[TIME] + function[TIME] 

1508 

1509 for cycle in cycles.values(): 

1510 profile.add_cycle(cycle) 

1511 

1512 # Compute derived events. 

1513 profile.validate() 

1514 profile.ratio(TIME_RATIO, TIME) 

1515 # Lacking call counts, fake call ratios based on total times. 

1516 profile.call_ratios(TOTAL_TIME_RATIO) 

1517 # The TOTAL_TIME_RATIO of functions is already set. Propagate that 

1518 # total time to the calls. (TOTAL_TIME is neither set nor used.) 

1519 for function in profile.functions.values(): 

1520 for call in function.calls.values(): 

1521 if call.ratio is not None: 

1522 callee = profile.functions[call.callee_id] 

1523 call[TOTAL_TIME_RATIO] = call.ratio * callee[TOTAL_TIME_RATIO] 

1524 

1525 return profile 

1526 

1527 

1528class CallgrindParser(LineParser): 

1529 """Parser for valgrind's callgrind tool. 

1530 

1531 See also: 

1532 - https://valgrind.org/docs/manual/cl-format.html 

1533 """ 

1534 

1535 _call_re = re.compile(r'^calls=\s*(\d+)\s+((\d+|\+\d+|-\d+|\*)\s+)+$') 

1536 

1537 def __init__(self, infile): 

1538 LineParser.__init__(self, infile) 

1539 

1540 # Textual positions 

1541 self.position_ids = {} 

1542 self.positions = {} 

1543 

1544 # Numeric positions 

1545 self.num_positions = 1 

1546 self.cost_positions = ['line'] 

1547 self.last_positions = [0] 

1548 

1549 # Events 

1550 self.num_events = 0 

1551 self.cost_events = [] 

1552 

1553 self.profile = Profile() 

1554 self.profile[SAMPLES] = 0 

1555 

1556 def parse(self): 

1557 # read lookahead 

1558 self.readline() 

1559 

1560 self.parse_key('version') 

1561 self.parse_key('creator') 

1562 while self.parse_part(): 

1563 pass 

1564 if not self.eof(): # pragma: no cover 

1565 sys.stderr.write('warning: line %u: unexpected line\n' % self.line_no) 

1566 sys.stderr.write('%s\n' % self.lookahead()) 

1567 

1568 # compute derived data 

1569 self.profile.validate() 

1570 self.profile.find_cycles() 

1571 self.profile.ratio(TIME_RATIO, SAMPLES) 

1572 self.profile.call_ratios(SAMPLES2) 

1573 self.profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

1574 

1575 return self.profile 

1576 

1577 def parse_part(self): 

1578 if not self.parse_header_line(): 

1579 return False 

1580 while self.parse_header_line(): 

1581 pass 

1582 if not self.parse_body_line(): 

1583 return False 

1584 while self.parse_body_line(): 

1585 pass 

1586 return True 

1587 

1588 def parse_header_line(self): 

1589 return \ 

1590 self.parse_empty() or \ 

1591 self.parse_part_detail() or \ 

1592 self.parse_description() or \ 

1593 self.parse_event_specification() or \ 

1594 self.parse_cost_line_def() or \ 

1595 self.parse_cost_summary() 

1596 

1597 _detail_keys = set(('cmd', 'pid', 'thread', 'part')) 

1598 

1599 def parse_part_detail(self): 

1600 return self.parse_keys(self._detail_keys) 

1601 

1602 def parse_description(self): 

1603 return self.parse_key('desc') is not None 

1604 

1605 def parse_event_specification(self): 

1606 event = self.parse_key('event') 

1607 if event is None: 

1608 return False 

1609 return True 

1610 

1611 def parse_cost_line_def(self): 

1612 pair = self.parse_keys(('events', 'positions')) 

1613 if pair is None: 

1614 return False 

1615 key, value = pair 

1616 items = value.split() 

1617 if key == 'events': 

1618 self.num_events = len(items) 

1619 self.cost_events = items 

1620 if key == 'positions': 

1621 self.num_positions = len(items) 

1622 self.cost_positions = items 

1623 self.last_positions = [0]*self.num_positions 

1624 return True 

1625 

1626 def parse_cost_summary(self): 

1627 pair = self.parse_keys(('summary', 'totals')) 

1628 if pair is None: 

1629 return False 

1630 return True 

1631 

1632 def parse_body_line(self): 

1633 return \ 

1634 self.parse_empty() or \ 

1635 self.parse_cost_line() or \ 

1636 self.parse_position_spec() or \ 

1637 self.parse_association_spec() 

1638 

1639 __subpos_re = r'(0x[0-9a-fA-F]+|\d+|\+\d+|-\d+|\*)' 

1640 _cost_re = re.compile(r'^' + 

1641 __subpos_re + r'( +' + __subpos_re + r')*' + 

1642 r'( +\d+)*' + 

1643 '$') 

1644 

1645 def parse_cost_line(self, calls=None): 

1646 line = self.lookahead().rstrip() 

1647 mo = self._cost_re.match(line) 

1648 if not mo: 

1649 return False 

1650 

1651 function = self.get_function() 

1652 

1653 if calls is None: 

1654 # Unlike other aspects, call object (cob) is relative not to the 

1655 # last call object, but to the caller's object (ob), so try to 

1656 # update it when processing a functions cost line 

1657 try: 

1658 self.positions['cob'] = self.positions['ob'] 

1659 except KeyError: 

1660 pass 

1661 

1662 values = line.split() 

1663 assert len(values) <= self.num_positions + self.num_events 

1664 

1665 positions = values[0 : self.num_positions] 

1666 events = values[self.num_positions : ] 

1667 events += ['0']*(self.num_events - len(events)) 

1668 

1669 for i in range(self.num_positions): 

1670 position = positions[i] 

1671 if position == '*': 

1672 position = self.last_positions[i] 

1673 elif position[0] in '-+': 

1674 position = self.last_positions[i] + int(position) 

1675 elif position.startswith('0x'): 

1676 position = int(position, 16) 

1677 else: 

1678 position = int(position) 

1679 self.last_positions[i] = position 

1680 

1681 events = [float(event) for event in events] 

1682 

1683 if calls is None: 

1684 function[SAMPLES] += events[0] 

1685 self.profile[SAMPLES] += events[0] 

1686 else: 

1687 callee = self.get_callee() 

1688 callee.called += calls 

1689 

1690 try: 

1691 call = function.calls[callee.id] 

1692 except KeyError: 

1693 call = Call(callee.id) 

1694 call[CALLS] = calls 

1695 call[SAMPLES2] = events[0] 

1696 function.add_call(call) 

1697 else: 

1698 call[CALLS] += calls 

1699 call[SAMPLES2] += events[0] 

1700 

1701 self.consume() 

1702 return True 

1703 

1704 def parse_association_spec(self): 

1705 line = self.lookahead() 

1706 if not line.startswith('calls='): 

1707 return False 

1708 

1709 _, values = line.split('=', 1) 

1710 values = values.strip().split() 

1711 calls = int(values[0]) 

1712 call_position = values[1:] 

1713 self.consume() 

1714 

1715 self.parse_cost_line(calls) 

1716 

1717 return True 

1718 

1719 _position_re = re.compile(r'^(?P<position>[cj]?(?:ob|fl|fi|fe|fn))=\s*(?:\((?P<id>\d+)\))?(?:\s*(?P<name>.+))?') 

1720 

1721 _position_table_map = { 

1722 'ob': 'ob', 

1723 'fl': 'fl', 

1724 'fi': 'fl', 

1725 'fe': 'fl', 

1726 'fn': 'fn', 

1727 'cob': 'ob', 

1728 'cfl': 'fl', 

1729 'cfi': 'fl', 

1730 'cfe': 'fl', 

1731 'cfn': 'fn', 

1732 'jfi': 'fl', 

1733 } 

1734 

1735 _position_map = { 

1736 'ob': 'ob', 

1737 'fl': 'fl', 

1738 'fi': 'fl', 

1739 'fe': 'fl', 

1740 'fn': 'fn', 

1741 'cob': 'cob', 

1742 'cfl': 'cfl', 

1743 'cfi': 'cfl', 

1744 'cfe': 'cfl', 

1745 'cfn': 'cfn', 

1746 'jfi': 'jfi', 

1747 } 

1748 

1749 def parse_position_spec(self): 

1750 line = self.lookahead() 

1751 

1752 if line.startswith('jump=') or line.startswith('jcnd='): 

1753 self.consume() 

1754 return True 

1755 

1756 mo = self._position_re.match(line) 

1757 if not mo: 

1758 return False 

1759 

1760 position, id, name = mo.groups() 

1761 if id: 

1762 table = self._position_table_map[position] 

1763 if name: 

1764 self.position_ids[(table, id)] = name 

1765 else: 

1766 name = self.position_ids.get((table, id), '') 

1767 self.positions[self._position_map[position]] = name 

1768 

1769 self.consume() 

1770 return True 

1771 

1772 def parse_empty(self): 

1773 if self.eof(): 

1774 return False 

1775 line = self.lookahead() 

1776 if line.strip(): 

1777 return False 

1778 self.consume() 

1779 return True 

1780 

1781 _key_re = re.compile(r'^(\w+):') 

1782 

1783 def parse_key(self, key): 

1784 pair = self.parse_keys((key,)) 

1785 if not pair: 

1786 return None 

1787 key, value = pair 

1788 return value 

1789 

1790 def parse_keys(self, keys): 

1791 line = self.lookahead() 

1792 mo = self._key_re.match(line) 

1793 if not mo: 

1794 return None 

1795 key, value = line.split(':', 1) 

1796 if key not in keys: 

1797 return None 

1798 value = value.strip() 

1799 self.consume() 

1800 return key, value 

1801 

1802 def make_function(self, module, filename, name): 

1803 # FIXME: module and filename are not being tracked reliably 

1804 #id = '|'.join((module, filename, name)) 

1805 id = name 

1806 try: 

1807 function = self.profile.functions[id] 

1808 except KeyError: 

1809 function = Function(id, name) 

1810 if module: 

1811 function.module = os.path.basename(module) 

1812 function[SAMPLES] = 0 

1813 function.called = 0 

1814 self.profile.add_function(function) 

1815 return function 

1816 

1817 def get_function(self): 

1818 module = self.positions.get('ob', '') 

1819 filename = self.positions.get('fl', '') 

1820 function = self.positions.get('fn', '') 

1821 return self.make_function(module, filename, function) 

1822 

1823 def get_callee(self): 

1824 module = self.positions.get('cob', '') 

1825 filename = self.positions.get('cfi', '') 

1826 function = self.positions.get('cfn', '') 

1827 return self.make_function(module, filename, function) 

1828 

1829 def readline(self): 

1830 # Override LineParser.readline to ignore comment lines 

1831 while True: 

1832 LineParser.readline(self) 

1833 if self.eof() or not self.lookahead().startswith('#'): 

1834 break 

1835 

1836 

1837class PerfParser(LineParser): 

1838 """Parser for linux perf callgraph output. 

1839 

1840 It expects output generated with 

1841 

1842 perf record -g 

1843 perf script | gprof2dot.py --format=perf 

1844 """ 

1845 

1846 def __init__(self, infile): 

1847 LineParser.__init__(self, infile) 

1848 self.profile = Profile() 

1849 

1850 def readline(self): 

1851 # Override LineParser.readline to ignore comment lines 

1852 while True: 

1853 LineParser.readline(self) 

1854 if self.eof() or not self.lookahead().startswith('#'): 

1855 break 

1856 

1857 def parse(self): 

1858 # read lookahead 

1859 self.readline() 

1860 

1861 profile = self.profile 

1862 profile[SAMPLES] = 0 

1863 while not self.eof(): 

1864 self.parse_event() 

1865 

1866 # compute derived data 

1867 profile.validate() 

1868 profile.find_cycles() 

1869 profile.ratio(TIME_RATIO, SAMPLES) 

1870 profile.call_ratios(SAMPLES2) 

1871 if totalMethod == "callratios": 

1872 # Heuristic approach. TOTAL_SAMPLES is unused. 

1873 profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

1874 elif totalMethod == "callstacks": 

1875 # Use the actual call chains for functions. 

1876 profile[TOTAL_SAMPLES] = profile[SAMPLES] 

1877 profile.ratio(TOTAL_TIME_RATIO, TOTAL_SAMPLES) 

1878 # Then propagate that total time to the calls. 

1879 for function in profile.functions.values(): 

1880 for call in function.calls.values(): 

1881 if call.ratio is not None: 

1882 callee = profile.functions[call.callee_id] 

1883 call[TOTAL_TIME_RATIO] = call.ratio * callee[TOTAL_TIME_RATIO] 

1884 else: # pragma: no cover 

1885 assert False 

1886 

1887 return profile 

1888 

1889 def parse_event(self): 

1890 if self.eof(): 

1891 return 

1892 

1893 line = self.consume() 

1894 assert line 

1895 

1896 callchain = self.parse_callchain() 

1897 if not callchain: 

1898 return 

1899 

1900 callee = callchain[0] 

1901 callee[SAMPLES] += 1 

1902 self.profile[SAMPLES] += 1 

1903 

1904 for caller in callchain[1:]: 

1905 try: 

1906 call = caller.calls[callee.id] 

1907 except KeyError: 

1908 call = Call(callee.id) 

1909 call[SAMPLES2] = 1 

1910 caller.add_call(call) 

1911 else: 

1912 call[SAMPLES2] += 1 

1913 

1914 callee = caller 

1915 

1916 # Increment TOTAL_SAMPLES only once on each function. 

1917 stack = set(callchain) 

1918 for function in stack: 

1919 function[TOTAL_SAMPLES] += 1 

1920 

1921 def parse_callchain(self): 

1922 frames = [] 

1923 while self.lookahead(): 

1924 frames.append(self.parse_call()) 

1925 if self.lookahead() == '': 

1926 self.consume() 

1927 

1928 # perf prints inlined frames as "addr func+off (inlined)". The frame 

1929 # they were inlined into isn't always next, nor at the same address, 

1930 # so attribute each one to the module of the real frame in this call 

1931 # chain with the nearest address, as modules are mapped far apart. 

1932 real_frames = [(int(address, 16), module) for address, _, module in frames if module != 'inlined'] 

1933 callchain = [] 

1934 for address, function_name, module in frames: 

1935 if module == 'inlined': 

1936 if real_frames: 

1937 address = int(address, 16) 

1938 module = min(real_frames, key=lambda frame: abs(frame[0] - address))[1] 

1939 else: 

1940 module = None 

1941 callchain.append(self.get_function(function_name, module)) 

1942 return callchain 

1943 

1944 call_re = re.compile(r'^\s+(?P<address>[0-9a-fA-F]+)\s+(?P<symbol>.*)\s+\((?P<module>.*)\)$') 

1945 addr2_re = re.compile(r'\+0x[0-9a-fA-F]+$') 

1946 

1947 def parse_call(self): 

1948 """Parse one call chain line into an (address, function name, module) tuple.""" 

1949 line = self.consume() 

1950 mo = self.call_re.match(line) 

1951 if not mo: 

1952 sys.stderr.write('error: unexpected perf script line: %r\n' % line) 

1953 sys.stderr.write('note: gprof2dot needs call chains; record with `perf record -g`\n') 

1954 sys.exit(1) 

1955 

1956 function_name = mo.group('symbol') 

1957 

1958 # If present, amputate program counter from function name. 

1959 if function_name: 

1960 function_name = re.sub(self.addr2_re, '', function_name) 

1961 

1962 if not function_name or function_name == '[unknown]': 

1963 function_name = mo.group('address') 

1964 

1965 return mo.group('address'), function_name, mo.group('module') 

1966 

1967 def get_function(self, function_name, module): 

1968 function_id = function_name + ':' + (module or '') 

1969 

1970 try: 

1971 function = self.profile.functions[function_id] 

1972 except KeyError: 

1973 function = Function(function_id, function_name) 

1974 if module is not None: 

1975 function.module = os.path.basename(module) 

1976 function[SAMPLES] = 0 

1977 function[TOTAL_SAMPLES] = 0 

1978 self.profile.add_function(function) 

1979 

1980 return function 

1981 

1982 

1983class SleepyParser(Parser): 

1984 """Parser for Very Sleepy profile output (.sleepy capture files). 

1985 

1986 See also: 

1987 - http://www.codersnotes.com/sleepy/ 

1988 - https://github.com/VerySleepy/verysleepy 

1989 """ 

1990 

1991 stdinInput = False 

1992 

1993 def __init__(self, filename): 

1994 Parser.__init__(self) 

1995 

1996 from zipfile import ZipFile 

1997 

1998 self.database = ZipFile(filename) 

1999 

2000 self.symbols = {} 

2001 self.calls = {} 

2002 

2003 self.profile = Profile() 

2004 

2005 _symbol_re = re.compile( 

2006 r'^(?P<id>\w+)' + 

2007 r'\s+"(?P<module>[^"]*)"' + 

2008 r'\s+"(?P<procname>[^"]*)"' + 

2009 r'\s+"(?P<sourcefile>[^"]*)"' + 

2010 r'\s+(?P<sourceline>\d+)$' 

2011 ) 

2012 

2013 def openEntry(self, name): 

2014 # Some versions of verysleepy use lowercase filenames 

2015 for database_name in self.database.namelist(): 

2016 if name.lower() == database_name.lower(): 

2017 name = database_name 

2018 break 

2019 

2020 return self.database.open(name, 'r') 

2021 

2022 def parse_symbols(self): 

2023 for line in self.openEntry('Symbols.txt'): 

2024 line = line.decode('UTF-8').rstrip('\r\n') 

2025 

2026 mo = self._symbol_re.match(line) 

2027 if mo: 

2028 symbol_id, module, procname, sourcefile, sourceline = mo.groups() 

2029 

2030 function_id = ':'.join([module, procname]) 

2031 

2032 try: 

2033 function = self.profile.functions[function_id] 

2034 except KeyError: 

2035 function = Function(function_id, procname) 

2036 function.module = module 

2037 function[SAMPLES] = 0 

2038 self.profile.add_function(function) 

2039 

2040 self.symbols[symbol_id] = function 

2041 

2042 def parse_callstacks(self): 

2043 for line in self.openEntry('Callstacks.txt'): 

2044 line = line.decode('UTF-8').rstrip('\r\n') 

2045 

2046 fields = line.split() 

2047 samples = float(fields[0]) 

2048 callstack = fields[1:] 

2049 

2050 callstack = [self.symbols[symbol_id] for symbol_id in callstack] 

2051 

2052 callee = callstack[0] 

2053 

2054 callee[SAMPLES] += samples 

2055 self.profile[SAMPLES] += samples 

2056 

2057 for caller in callstack[1:]: 

2058 try: 

2059 call = caller.calls[callee.id] 

2060 except KeyError: 

2061 call = Call(callee.id) 

2062 call[SAMPLES2] = samples 

2063 caller.add_call(call) 

2064 else: 

2065 call[SAMPLES2] += samples 

2066 

2067 callee = caller 

2068 

2069 def parse(self): 

2070 profile = self.profile 

2071 profile[SAMPLES] = 0 

2072 

2073 self.parse_symbols() 

2074 self.parse_callstacks() 

2075 

2076 # Compute derived events 

2077 profile.validate() 

2078 profile.find_cycles() 

2079 profile.ratio(TIME_RATIO, SAMPLES) 

2080 profile.call_ratios(SAMPLES2) 

2081 profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

2082 

2083 return profile 

2084 

2085 

2086class PstatsParser: 

2087 """Parser python profiling statistics saved with te pstats module.""" 

2088 

2089 stdinInput = False 

2090 multipleInput = True 

2091 

2092 def __init__(self, *filename): 

2093 import pstats 

2094 try: 

2095 # Discard the messages pstats prints on failure, as stdout may be 

2096 # our output. 

2097 self.stats = pstats.Stats(*filename, stream=io.StringIO()) 

2098 except ValueError: # pragma: no cover 

2099 sys.stderr.write('error: failed to load %s, maybe they are generated by different python version?\n' % ', '.join(filename)) 

2100 sys.exit(1) 

2101 except TypeError: 

2102 # pstats before 3.15 can't read the files written by Python 3.15's 

2103 # sampling profiler (`python -m profiling.sampling --pstats`). 

2104 if sys.version_info >= (3, 15): # pragma: no cover 

2105 raise 

2106 sys.stderr.write('error: failed to load %s, maybe written by a newer Python, such as 3.15\'s sampling profiler?\n' % ', '.join(filename)) 

2107 sys.stderr.write('note: run gprof2dot with that Python version instead (this is Python %u.%u)\n' % sys.version_info[:2]) 

2108 sys.exit(EXIT_UNSUPPORTED) 

2109 self.profile = Profile() 

2110 self.function_ids = {} 

2111 

2112 def get_function_name(self, key): 

2113 filename, line, name = key 

2114 module = os.path.splitext(filename)[0] 

2115 module = os.path.basename(module) 

2116 return "%s:%d:%s" % (module, line, name) 

2117 

2118 def get_function(self, key): 

2119 try: 

2120 id = self.function_ids[key] 

2121 except KeyError: 

2122 id = len(self.function_ids) 

2123 name = self.get_function_name(key) 

2124 function = Function(id, name) 

2125 function.filename = key[0] 

2126 self.profile.functions[id] = function 

2127 self.function_ids[key] = id 

2128 else: 

2129 function = self.profile.functions[id] 

2130 return function 

2131 

2132 def parse(self): 

2133 self.profile[TIME] = 0.0 

2134 self.profile[TOTAL_TIME] = self.stats.total_tt 

2135 for fn, (cc, nc, tt, ct, callers) in self.stats.stats.items(): 

2136 callee = self.get_function(fn) 

2137 callee.called = nc 

2138 callee[TOTAL_TIME] = ct 

2139 callee[TIME] = tt 

2140 self.profile[TIME] += tt 

2141 self.profile[TOTAL_TIME] = max(self.profile[TOTAL_TIME], ct) 

2142 for fn, value in callers.items(): 

2143 caller = self.get_function(fn) 

2144 call = Call(callee.id) 

2145 if isinstance(value, tuple): 

2146 for i in range(0, len(value), 4): 

2147 nc, cc, tt, ct = value[i:i+4] 

2148 if CALLS in call: 

2149 call[CALLS] += cc 

2150 else: 

2151 call[CALLS] = cc 

2152 

2153 if TOTAL_TIME in call: 

2154 call[TOTAL_TIME] += ct 

2155 else: 

2156 call[TOTAL_TIME] = ct 

2157 

2158 else: 

2159 call[CALLS] = value 

2160 call[TOTAL_TIME] = ratio(value, nc)*ct 

2161 

2162 caller.add_call(call) 

2163 

2164 if False: 

2165 self.stats.print_stats() 

2166 self.stats.print_callees() 

2167 

2168 # Compute derived events 

2169 self.profile.validate() 

2170 self.profile.ratio(TIME_RATIO, TIME) 

2171 self.profile.ratio(TOTAL_TIME_RATIO, TOTAL_TIME) 

2172 

2173 return self.profile 

2174 

2175class DtraceParser(LineParser): 

2176 """Parser for DTrace aggregated ustack() output. 

2177 

2178 It expects output generated with 

2179 

2180 # Refer to https://github.com/brendangregg/FlameGraph#dtrace 

2181 # 60 seconds of user-level stacks, including time spent in-kernel, for PID 12345 at 97 Hertz 

2182 sudo dtrace -x ustackframes=100 -n 'profile-97 /pid == 12345/ { @[ustack()] = count(); } tick-60s { exit(0); }' -o out.user_stacks 

2183 

2184 # The dtrace output 

2185 gprof2dot.py -f dtrace out.user_stacks 

2186 

2187 # Notice: sometimes, the dtrace outputs format may be latin-1, and gprof2dot will fail to parse it. 

2188 # To solve this problem, you should use iconv to convert to UTF-8 explicitly. 

2189 # TODO: add an encoding flag to tell gprof2dot how to decode the profile file. 

2190 iconv -f ISO-8859-1 -t UTF-8 out.user_stacks | gprof2dot.py -f dtrace 

2191 """ 

2192 

2193 def __init__(self, infile): 

2194 LineParser.__init__(self, infile) 

2195 self.profile = Profile() 

2196 

2197 def readline(self): 

2198 # Override LineParser.readline to ignore comment lines 

2199 while True: 

2200 LineParser.readline(self) 

2201 if self.eof(): 

2202 break 

2203 

2204 line = self.lookahead().strip() 

2205 if line.startswith('CPU'): 

2206 # The format likes: 

2207 # CPU ID FUNCTION:NAME 

2208 # 1 29684 :tick-60s 

2209 # Skip next line 

2210 LineParser.readline(self) 

2211 elif not line == '': 

2212 break 

2213 

2214 

2215 def parse(self): 

2216 # read lookahead 

2217 self.readline() 

2218 

2219 profile = self.profile 

2220 profile[SAMPLES] = 0 

2221 while not self.eof(): 

2222 self.parse_event() 

2223 

2224 # compute derived data 

2225 profile.validate() 

2226 profile.find_cycles() 

2227 profile.ratio(TIME_RATIO, SAMPLES) 

2228 profile.call_ratios(SAMPLES2) 

2229 if totalMethod == "callratios": 

2230 # Heuristic approach. TOTAL_SAMPLES is unused. 

2231 profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

2232 elif totalMethod == "callstacks": 

2233 # Use the actual call chains for functions. 

2234 profile[TOTAL_SAMPLES] = profile[SAMPLES] 

2235 profile.ratio(TOTAL_TIME_RATIO, TOTAL_SAMPLES) 

2236 # Then propagate that total time to the calls. 

2237 for function in profile.functions.values(): 

2238 for call in function.calls.values(): 

2239 if call.ratio is not None: 

2240 callee = profile.functions[call.callee_id] 

2241 call[TOTAL_TIME_RATIO] = call.ratio * callee[TOTAL_TIME_RATIO] 

2242 else: # pragma: no cover 

2243 assert False 

2244 

2245 return profile 

2246 

2247 def parse_event(self): 

2248 if self.eof(): 

2249 return 

2250 

2251 callchain, count = self.parse_callchain() 

2252 if not callchain: 

2253 return 

2254 

2255 callee = callchain[0] 

2256 callee[SAMPLES] += count 

2257 self.profile[SAMPLES] += count 

2258 

2259 for caller in callchain[1:]: 

2260 try: 

2261 call = caller.calls[callee.id] 

2262 except KeyError: 

2263 call = Call(callee.id) 

2264 call[SAMPLES2] = count 

2265 caller.add_call(call) 

2266 else: 

2267 call[SAMPLES2] += count 

2268 

2269 callee = caller 

2270 

2271 # Increment TOTAL_SAMPLES only once on each function. 

2272 stack = set(callchain) 

2273 for function in stack: 

2274 function[TOTAL_SAMPLES] += count 

2275 

2276 

2277 def parse_callchain(self): 

2278 callchain = [] 

2279 count = 0 

2280 while self.lookahead(): 

2281 function, count = self.parse_call() 

2282 if function is None: 

2283 break 

2284 callchain.append(function) 

2285 return callchain, count 

2286 

2287 call_re = re.compile(r'^\s+(?P<module>.*)`(?P<symbol>.*)') 

2288 addr2_re = re.compile(r'\+0x[0-9a-fA-F]+$') 

2289 

2290 def parse_call(self): 

2291 line = self.consume() 

2292 mo = self.call_re.match(line) 

2293 if not mo: 

2294 # The line must be the stack count 

2295 return None, int(line.strip()) 

2296 

2297 function_name = mo.group('symbol') 

2298 

2299 # If present, amputate program counter from function name. 

2300 if function_name: 

2301 function_name = re.sub(self.addr2_re, '', function_name) 

2302 

2303 # if not function_name or function_name == '[unknown]': 

2304 # function_name = mo.group('address') 

2305 

2306 module = mo.group('module') 

2307 

2308 function_id = function_name + ':' + module 

2309 

2310 try: 

2311 function = self.profile.functions[function_id] 

2312 except KeyError: 

2313 function = Function(function_id, function_name) 

2314 function.module = os.path.basename(module) 

2315 function[SAMPLES] = 0 

2316 function[TOTAL_SAMPLES] = 0 

2317 self.profile.add_function(function) 

2318 

2319 return function, None 

2320 

2321 

2322class CollapseParser(LineParser): 

2323 """Parser for the output of stackcollapse 

2324 

2325 (from https://github.com/brendangregg/FlameGraph) 

2326 """ 

2327 

2328 def __init__(self, infile): 

2329 LineParser.__init__(self, infile) 

2330 self.profile = Profile() 

2331 

2332 def parse(self): 

2333 profile = self.profile 

2334 profile[SAMPLES] = 0 

2335 

2336 self.readline() 

2337 while not self.eof(): 

2338 self.parse_event() 

2339 

2340 # compute derived data 

2341 profile.validate() 

2342 profile.find_cycles() 

2343 profile.ratio(TIME_RATIO, SAMPLES) 

2344 profile.call_ratios(SAMPLES2) 

2345 if totalMethod == "callratios": 

2346 # Heuristic approach. TOTAL_SAMPLES is unused. 

2347 profile.integrate(TOTAL_TIME_RATIO, TIME_RATIO) 

2348 elif totalMethod == "callstacks": 

2349 # Use the actual call chains for functions. 

2350 profile[TOTAL_SAMPLES] = profile[SAMPLES] 

2351 profile.ratio(TOTAL_TIME_RATIO, TOTAL_SAMPLES) 

2352 # Then propagate that total time to the calls. 

2353 for function in profile.functions.values(): 

2354 for call in function.calls.values(): 

2355 if call.ratio is not None: 

2356 callee = profile.functions[call.callee_id] 

2357 call[TOTAL_TIME_RATIO] = call.ratio * callee[TOTAL_TIME_RATIO] 

2358 else: # pragma: no cover 

2359 assert False 

2360 

2361 return profile 

2362 

2363 def parse_event(self): 

2364 line = self.consume() 

2365 

2366 stack, count = line.rsplit(' ',maxsplit=1) 

2367 count=int(count) 

2368 self.profile[SAMPLES] += count 

2369 

2370 calls = stack.split(';') 

2371 functions = [self._make_function(call) for call in calls] 

2372 

2373 functions[-1][SAMPLES] += count 

2374 

2375 # TOTAL_SAMPLES excludes loops 

2376 for func in set(functions): 

2377 func[TOTAL_SAMPLES] += count 

2378 

2379 # add call data 

2380 callee = functions[-1] 

2381 for caller in reversed(functions[:-1]): 

2382 call = caller.calls.get(callee.id) 

2383 if call is None: 

2384 call = Call(callee.id) 

2385 call[SAMPLES2] = 0 

2386 caller.add_call(call) 

2387 call[SAMPLES2] += count 

2388 callee = caller 

2389 

2390 call_re = re.compile(r'^(?P<func>[^ ]+) \((?P<file>.*):(?P<line>[0-9]+)\)$') 

2391 

2392 def _make_function(self, call): 

2393 """turn a call str into a Function 

2394 

2395 takes a call site, as found between semicolons in the input, and returns 

2396 a Function definition corresponding to that call site. 

2397 """ 

2398 mo = self.call_re.match(call) 

2399 if mo: 

2400 name, module, line = mo.groups() 

2401 func_id = "%s:%s" % (module, name) 

2402 else: 

2403 name = func_id = call 

2404 module = None 

2405 

2406 func = self.profile.functions.get(func_id) 

2407 if func is None: 

2408 func = Function(func_id, name) 

2409 func.module = module 

2410 func[SAMPLES] = 0 

2411 func[TOTAL_SAMPLES] = 0 

2412 self.profile.add_function(func) 

2413 return func 

2414 

2415 

2416formats = { 

2417 "axe": AXEParser, 

2418 "callgrind": CallgrindParser, 

2419 "collapse": CollapseParser, 

2420 "json": JsonParser, 

2421 "perf": PerfParser, 

2422 "prof": GprofParser, 

2423 "pstats": PstatsParser, 

2424 "sleepy": SleepyParser, 

2425 "dtrace": DtraceParser, 

2426} 

2427 

2428 

2429######################################################################## 

2430# Output 

2431 

2432 

2433class Theme: 

2434 

2435 def __init__(self, 

2436 bgcolor = (0.0, 0.0, 1.0), 

2437 mincolor = (0.0, 0.0, 0.0), 

2438 maxcolor = (0.0, 0.0, 1.0), 

2439 fontname = "Arial", 

2440 fontcolor = "white", 

2441 nodestyle = "filled", 

2442 minfontsize = 10.0, 

2443 maxfontsize = 10.0, 

2444 minpenwidth = 0.5, 

2445 maxpenwidth = 4.0, 

2446 gamma = 2.2, 

2447 skew = 1.0): 

2448 self.bgcolor = bgcolor 

2449 self.mincolor = mincolor 

2450 self.maxcolor = maxcolor 

2451 self.fontname = fontname 

2452 self.fontcolor = fontcolor 

2453 self.nodestyle = nodestyle 

2454 self.minfontsize = minfontsize 

2455 self.maxfontsize = maxfontsize 

2456 self.minpenwidth = minpenwidth 

2457 self.maxpenwidth = maxpenwidth 

2458 self.gamma = gamma 

2459 self.skew = skew 

2460 

2461 def graph_bgcolor(self): 

2462 return self.hsl_to_rgb(*self.bgcolor) 

2463 

2464 def graph_fontname(self): 

2465 return self.fontname 

2466 

2467 def graph_fontcolor(self): 

2468 return self.fontcolor 

2469 

2470 def node_bgcolor(self, weight): 

2471 return self.color(weight) 

2472 

2473 def node_fgcolor(self, weight): 

2474 if self.nodestyle == "filled": 

2475 return self.graph_bgcolor() 

2476 else: 

2477 return self.color(weight) 

2478 

2479 def node_fontsize(self, weight): 

2480 return self.fontsize(weight) 

2481 

2482 def node_style(self): 

2483 return self.nodestyle 

2484 

2485 def edge_color(self, weight): 

2486 return self.color(weight) 

2487 

2488 def edge_fontsize(self, weight): 

2489 return self.fontsize(weight) 

2490 

2491 def edge_penwidth(self, weight): 

2492 return max(weight*self.maxpenwidth, self.minpenwidth) 

2493 

2494 def edge_arrowsize(self, weight): 

2495 return 0.5 * math.sqrt(self.edge_penwidth(weight)) 

2496 

2497 def fontsize(self, weight): 

2498 return max(weight**2 * self.maxfontsize, self.minfontsize) 

2499 

2500 def color(self, weight): 

2501 weight = min(max(weight, 0.0), 1.0) 

2502 

2503 hmin, smin, lmin = self.mincolor 

2504 hmax, smax, lmax = self.maxcolor 

2505 

2506 assert self.skew >= 0.0 

2507 if self.skew == 1.0: 

2508 h = hmin + weight*(hmax - hmin) 

2509 s = smin + weight*(smax - smin) 

2510 l = lmin + weight*(lmax - lmin) 

2511 else: 

2512 base = self.skew 

2513 h = hmin + ((hmax-hmin)*(-1.0 + (base ** weight)) / (base - 1.0)) 

2514 s = smin + ((smax-smin)*(-1.0 + (base ** weight)) / (base - 1.0)) 

2515 l = lmin + ((lmax-lmin)*(-1.0 + (base ** weight)) / (base - 1.0)) 

2516 

2517 return self.hsl_to_rgb(h, s, l) 

2518 

2519 def hsl_to_rgb(self, h, s, l): 

2520 """Convert a color from HSL color-model to RGB. 

2521 

2522 See also: 

2523 - http://www.w3.org/TR/css3-color/#hsl-color 

2524 """ 

2525 

2526 h = h % 1.0 

2527 s = min(max(s, 0.0), 1.0) 

2528 l = min(max(l, 0.0), 1.0) 

2529 

2530 if l <= 0.5: 

2531 m2 = l*(s + 1.0) 

2532 else: 

2533 m2 = l + s - l*s 

2534 m1 = l*2.0 - m2 

2535 r = self._hue_to_rgb(m1, m2, h + 1.0/3.0) 

2536 g = self._hue_to_rgb(m1, m2, h) 

2537 b = self._hue_to_rgb(m1, m2, h - 1.0/3.0) 

2538 

2539 # Apply gamma correction 

2540 r **= self.gamma 

2541 g **= self.gamma 

2542 b **= self.gamma 

2543 

2544 return (r, g, b) 

2545 

2546 def _hue_to_rgb(self, m1, m2, h): 

2547 if h < 0.0: 

2548 h += 1.0 

2549 elif h > 1.0: 

2550 h -= 1.0 

2551 if h*6 < 1.0: 

2552 return m1 + (m2 - m1)*h*6.0 

2553 elif h*2 < 1.0: 

2554 return m2 

2555 elif h*3 < 2.0: 

2556 return m1 + (m2 - m1)*(2.0/3.0 - h)*6.0 

2557 else: 

2558 return m1 

2559 

2560 

2561TEMPERATURE_COLORMAP = Theme( 

2562 mincolor = (2.0/3.0, 0.80, 0.25), # dark blue 

2563 maxcolor = (0.0, 1.0, 0.5), # satured red 

2564 gamma = 1.0 

2565) 

2566 

2567PINK_COLORMAP = Theme( 

2568 mincolor = (0.0, 1.0, 0.90), # pink 

2569 maxcolor = (0.0, 1.0, 0.5), # satured red 

2570) 

2571 

2572GRAY_COLORMAP = Theme( 

2573 mincolor = (0.0, 0.0, 0.85), # light gray 

2574 maxcolor = (0.0, 0.0, 0.0), # black 

2575) 

2576 

2577BW_COLORMAP = Theme( 

2578 minfontsize = 8.0, 

2579 maxfontsize = 24.0, 

2580 mincolor = (0.0, 0.0, 0.0), # black 

2581 maxcolor = (0.0, 0.0, 0.0), # black 

2582 minpenwidth = 0.1, 

2583 maxpenwidth = 8.0, 

2584) 

2585 

2586PRINT_COLORMAP = Theme( 

2587 minfontsize = 18.0, 

2588 maxfontsize = 30.0, 

2589 fontcolor = "black", 

2590 nodestyle = "solid", 

2591 mincolor = (0.0, 0.0, 0.0), # black 

2592 maxcolor = (0.0, 0.0, 0.0), # black 

2593 minpenwidth = 0.1, 

2594 maxpenwidth = 8.0, 

2595) 

2596 

2597 

2598themes = { 

2599 "color": TEMPERATURE_COLORMAP, 

2600 "pink": PINK_COLORMAP, 

2601 "gray": GRAY_COLORMAP, 

2602 "bw": BW_COLORMAP, 

2603 "print": PRINT_COLORMAP, 

2604} 

2605 

2606 

2607def sorted_iteritems(d): 

2608 # Used mostly for result reproducibility (while testing.) 

2609 keys = list(d.keys()) 

2610 keys.sort() 

2611 for key in keys: 

2612 value = d[key] 

2613 yield key, value 

2614 

2615 

2616class DotWriter: 

2617 """Writer for the DOT language. 

2618 

2619 See also: 

2620 - "The DOT Language" specification 

2621 http://www.graphviz.org/doc/info/lang.html 

2622 """ 

2623 

2624 strip = False 

2625 wrap = False 

2626 

2627 def __init__(self, fp): 

2628 self.fp = fp 

2629 

2630 def wrap_function_name(self, name): 

2631 """Split the function name on multiple lines.""" 

2632 

2633 if len(name) > 32: 

2634 ratio = 2.0/3.0 

2635 height = max(int(len(name)/(1.0 - ratio) + 0.5), 1) 

2636 width = max(len(name)/height, 32) 

2637 # TODO: break lines in symbols 

2638 name = textwrap.fill(name, width, break_long_words=False) 

2639 

2640 # Take away spaces 

2641 name = name.replace(", ", ",") 

2642 name = name.replace("> >", ">>") 

2643 name = name.replace("> >", ">>") # catch consecutive 

2644 

2645 return name 

2646 

2647 # dot can't parse quoted strings longer than YY_BUF_SIZE, which defaults 

2648 # to 16K. But some annotated C++ functions (e.g., boost, 

2649 # https://github.com/jrfonseca/gprof2dot/issues/30) can exceed that. 

2650 MAX_FUNCTION_NAME = 4096 

2651 

2652 def function_name_label(self, function): 

2653 """Function name as shown in its node: stripped, truncated, and wrapped 

2654 as requested.""" 

2655 

2656 if self.strip: 

2657 name = function.stripped_name() 

2658 else: 

2659 name = function.name 

2660 

2661 if len(name) >= self.MAX_FUNCTION_NAME: 

2662 sys.stderr.write('warning: truncating function name with %u chars (%s)\n' % (len(name), name[:32] + '...')) 

2663 name = name[:self.MAX_FUNCTION_NAME - 1] + chr(0x2026) 

2664 

2665 if self.wrap: 

2666 name = self.wrap_function_name(name) 

2667 

2668 return name 

2669 

2670 show_function_events = [TOTAL_TIME_RATIO, TIME_RATIO] 

2671 show_edge_events = [TOTAL_TIME_RATIO, CALLS] 

2672 

2673 def graphs_compare(self, profile1, profile2, theme, options): 

2674 self.begin_graph() 

2675 

2676 fontname = theme.graph_fontname() 

2677 fontcolor = theme.graph_fontcolor() 

2678 nodestyle = theme.node_style() 

2679 

2680 tolerance, only_slower, only_faster, color_by_difference = ( 

2681 options.tolerance, options.only_slower, options.only_faster, options.color_by_difference) 

2682 self.attr('graph', fontname=fontname, ranksep=0.25, nodesep=0.125) 

2683 self.attr('node', fontname=fontname, style=nodestyle, fontcolor=fontcolor, width=0, height=0) 

2684 self.attr('edge', fontname=fontname) 

2685 

2686 # Match functions across profiles by name, since ids are not stable 

2687 # between profiles. Names shared by several functions (e.g., static 

2688 # functions in different modules) are told apart by module too. The 

2689 # module is not used otherwise, as some parsers (e.g., callgrind) don't 

2690 # report it consistently between profiles. 

2691 duplicate_names = set() 

2692 for profile in (profile1, profile2): 

2693 names = set() 

2694 for function in profile.functions.values(): 

2695 if function.name in names: 

2696 duplicate_names.add(function.name) 

2697 names.add(function.name) 

2698 

2699 def function_key(function): 

2700 if function.name in duplicate_names: 

2701 return function.module, function.name 

2702 return function.name 

2703 

2704 functions2 = {function_key(function): function for _, function in sorted_iteritems(profile2.functions)} 

2705 

2706 for _, function1 in sorted_iteritems(profile1.functions): 

2707 labels = [] 

2708 function2 = None 

2709 

2710 try: 

2711 function2 = functions2[function_key(function1)] 

2712 if color_by_difference: 

2713 min_diff, max_diff = min_max_difference(profile1, profile2) 

2714 labels.append(self.function_name_label(function1)) 

2715 weight_difference = 0 

2716 shape = 'box' 

2717 orientation = '0' 

2718 for event in self.show_function_events: 

2719 if event in function1.events: 

2720 event1 = function1[event] 

2721 event2 = function2[event] 

2722 

2723 difference = abs(event1 - event2) * 100 

2724 

2725 if event == TOTAL_TIME_RATIO: 

2726 weight_difference = difference 

2727 if difference >= tolerance: 

2728 if event2 > event1 and not only_faster: 

2729 shape = 'cds' 

2730 label = (f'{event.format(event1)} +' 

2731 f' {round_difference(difference, tolerance)}%') 

2732 elif event2 < event1 and not only_slower: 

2733 orientation = "90" 

2734 shape = 'cds' 

2735 label = (f'{event.format(event1)} - ' 

2736 f'{round_difference(difference, tolerance)}%') 

2737 else: 

2738 # protection to not color by difference if we choose to show only_faster/only_slower 

2739 weight_difference = 0 

2740 label = event.format(function1[event]) 

2741 else: 

2742 weight_difference = 0 

2743 label = event.format(function1[event]) 

2744 else: 

2745 if difference >= tolerance: 

2746 if event2 > event1: 

2747 label = (f'{event.format(event1)} +' 

2748 f' {round_difference(difference, tolerance)}%') 

2749 elif event2 < event1: 

2750 label = (f'{event.format(event1)} - ' 

2751 f'{round_difference(difference, tolerance)}%') 

2752 else: 

2753 label = event.format(function1[event]) 

2754 

2755 labels.append(label) 

2756 if function1.called is not None: 

2757 labels.append(f"{function1.called} {MULTIPLICATION_SIGN}/ {function2.called} {MULTIPLICATION_SIGN}") 

2758 

2759 except KeyError: 

2760 shape = 'box' 

2761 orientation = '0' 

2762 weight_difference = 0 

2763 if function1.process is not None: 

2764 labels.append(function1.process) 

2765 if function1.module is not None: 

2766 labels.append(function1.module) 

2767 

2768 if color_by_difference: 

2769 min_diff, max_diff = 0, 0 

2770 labels.append(self.function_name_label(function1)) 

2771 

2772 for event in self.show_function_events: 

2773 if event in function1.events: 

2774 label = event.format(function1[event]) 

2775 labels.append(label) 

2776 if function1.called is not None: 

2777 labels.append("%u%s" % (function1.called, MULTIPLICATION_SIGN)) 

2778 

2779 if color_by_difference and weight_difference: 

2780 # min and max is calculated whe color_by_difference is true 

2781 weight = rescale_difference(weight_difference, min_diff, max_diff) 

2782 

2783 elif function1.weight is not None and not color_by_difference: 

2784 weight = function1.weight 

2785 else: 

2786 weight = 0.0 

2787 

2788 label = '\n'.join(labels) 

2789 

2790 self.node(function1.id, 

2791 label=label, 

2792 orientation=orientation, 

2793 color=self.color(theme.node_bgcolor(weight)), 

2794 shape=shape, 

2795 fontcolor=self.color(theme.node_fgcolor(weight)), 

2796 fontsize="%f" % theme.node_fontsize(weight), 

2797 tooltip=function1.filename, 

2798 ) 

2799 

2800 if function2 is not None: 

2801 calls2 = {call.callee_id: call for _, call in sorted_iteritems(function2.calls)} 

2802 else: 

2803 calls2 = {} 

2804 functions_by_id1 = {function.id: function for _, function in sorted_iteritems(profile1.functions)} 

2805 

2806 for _, call1 in sorted_iteritems(function1.calls): 

2807 labels = [] 

2808 try: 

2809 # if profiles do not have identical setups, callee_id will not be identical either 

2810 call_id1 = call1.callee_id 

2811 call_key = function_key(functions_by_id1[call_id1]) 

2812 call_id2 = functions2[call_key].id 

2813 call2 = calls2[call_id2] 

2814 for event in self.show_edge_events: 

2815 if event in call1.events: 

2816 label = f'{event.format(call1[event])} / {event.format(call2[event])}' 

2817 labels.append(label) 

2818 except KeyError: 

2819 for event in self.show_edge_events: 

2820 if event in call1.events: 

2821 label = f'{event.format(call1[event])}' 

2822 labels.append(label) 

2823 

2824 weight = 0 if color_by_difference else call1.weight 

2825 label = '\n'.join(labels) 

2826 self.edge(function1.id, call1.callee_id, 

2827 label=label, 

2828 color=self.color(theme.edge_color(weight)), 

2829 fontcolor=self.color(theme.edge_color(weight)), 

2830 fontsize="%.2f" % theme.edge_fontsize(weight), 

2831 penwidth="%.2f" % theme.edge_penwidth(weight), 

2832 labeldistance="%.2f" % theme.edge_penwidth(weight), 

2833 arrowsize="%.2f" % theme.edge_arrowsize(weight), 

2834 ) 

2835 self.end_graph() 

2836 

2837 def graph(self, profile, theme): 

2838 self.begin_graph() 

2839 

2840 fontname = theme.graph_fontname() 

2841 fontcolor = theme.graph_fontcolor() 

2842 nodestyle = theme.node_style() 

2843 

2844 self.attr('graph', fontname=fontname, ranksep=0.25, nodesep=0.125) 

2845 self.attr('node', fontname=fontname, shape="box", style=nodestyle, fontcolor=fontcolor, width=0, height=0) 

2846 self.attr('edge', fontname=fontname) 

2847 

2848 for _, function in sorted_iteritems(profile.functions): 

2849 labels = [] 

2850 if function.process is not None: 

2851 labels.append(function.process) 

2852 if function.module is not None: 

2853 labels.append(function.module) 

2854 

2855 labels.append(self.function_name_label(function)) 

2856 

2857 for event in self.show_function_events: 

2858 if event in function.events: 

2859 label = event.format(function[event]) 

2860 labels.append(label) 

2861 if function.called is not None: 

2862 labels.append("%u%s" % (function.called, MULTIPLICATION_SIGN)) 

2863 

2864 if function.weight is not None: 

2865 weight = function.weight 

2866 else: 

2867 weight = 0.0 

2868 

2869 label = '\n'.join(labels) 

2870 self.node(function.id, 

2871 label = label, 

2872 color = self.color(theme.node_bgcolor(weight)), 

2873 fontcolor = self.color(theme.node_fgcolor(weight)), 

2874 fontsize = "%.2f" % theme.node_fontsize(weight), 

2875 tooltip = function.filename, 

2876 ) 

2877 

2878 for _, call in sorted_iteritems(function.calls): 

2879 callee = profile.functions[call.callee_id] 

2880 

2881 labels = [] 

2882 for event in self.show_edge_events: 

2883 if event in call.events: 

2884 label = event.format(call[event]) 

2885 labels.append(label) 

2886 

2887 if call.weight is not None: 

2888 weight = call.weight 

2889 elif callee.weight is not None: 

2890 weight = callee.weight 

2891 else: 

2892 weight = 0.0 

2893 

2894 label = '\n'.join(labels) 

2895 

2896 self.edge(function.id, call.callee_id, 

2897 label = label, 

2898 color = self.color(theme.edge_color(weight)), 

2899 fontcolor = self.color(theme.edge_color(weight)), 

2900 fontsize = "%.2f" % theme.edge_fontsize(weight), 

2901 penwidth = "%.2f" % theme.edge_penwidth(weight), 

2902 labeldistance = "%.2f" % theme.edge_penwidth(weight), 

2903 arrowsize = "%.2f" % theme.edge_arrowsize(weight), 

2904 ) 

2905 

2906 self.end_graph() 

2907 

2908 def begin_graph(self): 

2909 self.write('digraph {\n') 

2910 # Work-around graphviz bug[1]: unnamed graphs have "%3" tooltip in SVG 

2911 # output. The bug was fixed upstream, but graphviz shipped in recent 

2912 # Linux distros (for example, Ubuntu 24.04) still has the bug. 

2913 # [1] https://gitlab.com/graphviz/graphviz/-/issues/1376 

2914 self.write('\ttooltip=" "\n') 

2915 

2916 def end_graph(self): 

2917 self.write('}\n') 

2918 

2919 def attr(self, what, **attrs): 

2920 self.write("\t") 

2921 self.write(what) 

2922 self.attr_list(attrs) 

2923 self.write(";\n") 

2924 

2925 def node(self, node, **attrs): 

2926 self.write("\t") 

2927 self.node_id(node) 

2928 self.attr_list(attrs) 

2929 self.write(";\n") 

2930 

2931 def edge(self, src, dst, **attrs): 

2932 self.write("\t") 

2933 self.node_id(src) 

2934 self.write(" -> ") 

2935 self.node_id(dst) 

2936 self.attr_list(attrs) 

2937 self.write(";\n") 

2938 

2939 def attr_list(self, attrs): 

2940 if not attrs: 

2941 return 

2942 self.write(' [') 

2943 first = True 

2944 for name, value in sorted_iteritems(attrs): 

2945 if value is None: 

2946 continue 

2947 if first: 

2948 first = False 

2949 else: 

2950 self.write(", ") 

2951 assert isinstance(name, str) 

2952 assert name.isidentifier() 

2953 self.write(name) 

2954 self.write('=') 

2955 self.id(value) 

2956 self.write(']') 

2957 

2958 def node_id(self, id): 

2959 # Node IDs need to be unique (can't be truncated) but dot doesn't allow 

2960 # IDs longer than 16384 characters, so use an hash instead for the huge 

2961 # C++ symbols that can arise, as seen in 

2962 # https://github.com/jrfonseca/gprof2dot/issues/99 

2963 if isinstance(id, str) and len(id) > 1024: 

2964 data = id.encode('utf-8') 

2965 digest = hashlib.sha1(data, usedforsecurity=False) 

2966 id = '_' + digest.hexdigest() 

2967 self.id(id) 

2968 

2969 # dot keywords, which must be quoted when used as ordinary identifiers. 

2970 _keywords = frozenset(('node', 'edge', 'graph', 'digraph', 'subgraph', 'strict')) 

2971 

2972 def id(self, id): 

2973 if isinstance(id, (int, float)): 

2974 s = str(id) 

2975 elif isinstance(id, str): 

2976 if id.isalnum() and not id[0].isdigit() and id.lower() not in self._keywords: 

2977 s = id 

2978 else: 

2979 s = self.escape(id) 

2980 else: # pragma: no cover 

2981 raise TypeError 

2982 self.write(s) 

2983 

2984 def color(self, rgb): 

2985 r, g, b = rgb 

2986 

2987 def float2int(f): 

2988 if f <= 0.0: 

2989 return 0 

2990 if f >= 1.0: 

2991 return 255 

2992 return int(255.0*f + 0.5) 

2993 

2994 return "#" + "".join(["%02x" % float2int(c) for c in (r, g, b)]) 

2995 

2996 def escape(self, s): 

2997 s = s.replace('\\', r'\\') 

2998 s = s.replace('\n', r'\n') 

2999 s = s.replace('\t', r'\t') 

3000 s = s.replace('"', r'\"') 

3001 return '"' + s + '"' 

3002 

3003 def write(self, s): 

3004 self.fp.write(s) 

3005 

3006 

3007 

3008######################################################################## 

3009# Main program 

3010 

3011 

3012def naturalJoin(values): 

3013 if len(values) >= 2: 

3014 return ', '.join(values[:-1]) + ' or ' + values[-1] 

3015 

3016 else: 

3017 return ''.join(values) 

3018 

3019 

3020def openInput(path): 

3021 """Open a text profile, consuming the byte order mark when there is one.""" 

3022 

3023 fp = open(path, 'rb') 

3024 bom = fp.read(2) 

3025 if bom in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): 

3026 # Default on Windows PowerShell (https://github.com/jrfonseca/gprof2dot/issues/88) 

3027 encoding = 'utf-16' 

3028 else: 

3029 encoding = 'utf-8-sig' 

3030 fp.seek(0) 

3031 return io.TextIOWrapper(fp, encoding=encoding) 

3032 

3033 

3034def main(argv=sys.argv[1:]): 

3035 """Main program.""" 

3036 

3037 global totalMethod, timeFormat 

3038 

3039 formatNames = list(formats.keys()) 

3040 formatNames.sort() 

3041 

3042 themeNames = list(themes.keys()) 

3043 themeNames.sort() 

3044 

3045 labelNames = list(labels.keys()) 

3046 labelNames.sort() 

3047 

3048 argparser = argparse.ArgumentParser( 

3049 usage="\n %(prog)s [options] [INPUT] ...") 

3050 argparser.add_argument( 

3051 '-o', '--output', metavar='OUTPUT', 

3052 dest="output", 

3053 help="output filename [stdout]") 

3054 argparser.add_argument( 

3055 '-n', '--node-thres', metavar='PERCENTAGE', 

3056 type=float, dest="node_thres", default=0.5, 

3057 help="eliminate nodes below this threshold [default: %(default)s]") 

3058 argparser.add_argument( 

3059 '-e', '--edge-thres', metavar='PERCENTAGE', 

3060 type=float, dest="edge_thres", default=0.1, 

3061 help="eliminate edges below this threshold [default: %(default)s]") 

3062 argparser.add_argument( 

3063 '-f', '--format', 

3064 choices=formatNames, 

3065 dest="format", default="prof", 

3066 help="profile format: %s [default: %%(default)s]" % naturalJoin(formatNames)) 

3067 argparser.add_argument( 

3068 '--total', 

3069 choices=('callratios', 'callstacks'), 

3070 dest="totalMethod", default=DEFAULT_TOTAL_METHOD, 

3071 help="preferred method of calculating total time: callratios or callstacks (affects only perf, dtrace and collapse formats) [default: %(default)s]") 

3072 argparser.add_argument( 

3073 '-c', '--colormap', 

3074 choices=themeNames, 

3075 dest="theme", default="color", 

3076 help="color map: %s [default: %%(default)s]" % naturalJoin(themeNames)) 

3077 argparser.add_argument( 

3078 '-s', '--strip', 

3079 action="store_true", 

3080 dest="strip", default=False, 

3081 help="strip function parameters, template parameters, and const modifiers from demangled C++ function names") 

3082 argparser.add_argument( 

3083 '--color-nodes-by-selftime', 

3084 action="store_true", 

3085 dest="color_nodes_by_selftime", default=False, 

3086 help="color nodes by self time, rather than by total time (sum of self and descendants)") 

3087 argparser.add_argument( 

3088 '--colour-nodes-by-selftime', 

3089 action="store_true", 

3090 dest="color_nodes_by_selftime", 

3091 help=argparse.SUPPRESS) 

3092 argparser.add_argument( 

3093 '-w', '--wrap', 

3094 action="store_true", 

3095 dest="wrap", default=False, 

3096 help="wrap function names") 

3097 argparser.add_argument( 

3098 '--show-samples', 

3099 action="store_true", 

3100 dest="show_samples", default=False, 

3101 help="show function samples") 

3102 argparser.add_argument( 

3103 '--time-format', 

3104 default=DEFAULT_TIME_FORMAT, 

3105 help="format to use for showing time values [default: %(default)s]") 

3106 argparser.add_argument( 

3107 '--node-label', metavar='MEASURE', 

3108 choices=labelNames, 

3109 action='append', 

3110 dest='node_labels', 

3111 help="measurements to on show the node (can be specified multiple times): %s [default: %s]" % ( 

3112 naturalJoin(labelNames), ', '.join(defaultLabelNames))) 

3113 # add option to show information on available entries () 

3114 argparser.add_argument( 

3115 '--list-functions', 

3116 dest="list_functions", default=None, 

3117 help="""\ 

3118list functions available for selection in -z or -l, requires selector argument 

3119( use '+' to select all). 

3120Recall that the selector argument is used with Unix/Bash globbing/pattern matching, 

3121and that entries are formatted '<pkg>:<linenum>:<function>'. When argument starts 

3122with '%%', a dump of all available information is performed for selected entries, 

3123 after removal of leading '%%'. 

3124""") 

3125 # add option to create subtree or show paths 

3126 argparser.add_argument( 

3127 '-z', '--root', 

3128 dest="root", default="", 

3129 help="prune call graph to show only descendants of specified root function") 

3130 argparser.add_argument( 

3131 '-l', '--leaf', 

3132 dest="leaf", default="", 

3133 help="prune call graph to show only ancestors of specified leaf function") 

3134 argparser.add_argument( 

3135 '--depth', 

3136 type=int, 

3137 dest="depth", default=-1, 

3138 help="prune call graph to show only descendants or ancestors until specified depth") 

3139 # add a new option to control skew of the colorization curve 

3140 argparser.add_argument( 

3141 '--skew', 

3142 type=float, dest="theme_skew", default=1.0, 

3143 help="skew the colorization curve. Values < 1.0 give more variety to lower percentages. Values > 1.0 give less variety to lower percentages") 

3144 # add option for filtering by file path 

3145 argparser.add_argument( 

3146 '-p', '--path', action="append", 

3147 dest="filter_paths", 

3148 help="filter all modules not in a specified path") 

3149 argparser.add_argument( 

3150 '--compare', 

3151 action="store_true", 

3152 dest="compare", default=False, 

3153 help="compare two graphs with almost identical structure. With this option two files should be provided." 

3154 "gprof2dot.py [options] --compare [file1] [file2] ...") 

3155 argparser.add_argument( 

3156 '--compare-tolerance', 

3157 type=float, dest="tolerance", default=0.001, 

3158 help="tolerance threshold for node difference (default=0.001%%)." 

3159 "If the difference is below this value the nodes are considered identical.") 

3160 argparser.add_argument( 

3161 '--compare-only-slower', 

3162 action="store_true", 

3163 dest="only_slower", default=False, 

3164 help="display comparison only for function which are slower in second graph.") 

3165 argparser.add_argument( 

3166 '--compare-only-faster', 

3167 action="store_true", 

3168 dest="only_faster", default=False, 

3169 help="display comparison only for function which are faster in second graph.") 

3170 argparser.add_argument( 

3171 '--compare-color-by-difference', 

3172 action="store_true", 

3173 dest="color_by_difference", default=False, 

3174 help="color nodes based on the value of the difference. " 

3175 "Nodes with the largest differences represent the hot spots.") 

3176 argparser.add_argument('input', nargs='*', metavar='INPUT', help='input stats') 

3177 options = argparser.parse_args(argv) 

3178 args = options.input 

3179 

3180 if len(args) > 1 and options.format != 'pstats' and not options.compare: # pragma: no cover 

3181 argparser.error('incorrect number of arguments') 

3182 

3183 try: 

3184 theme = themes[options.theme] 

3185 except KeyError: # pragma: no cover 

3186 argparser.error('invalid colormap \'%s\'' % options.theme) 

3187 

3188 # set skew on the theme now that it has been picked. 

3189 if not options.theme_skew >= 0.0: # pragma: no cover 

3190 argparser.error('skew must be non-negative') 

3191 theme.skew = options.theme_skew 

3192 

3193 totalMethod = options.totalMethod 

3194 timeFormat = options.time_format 

3195 

3196 try: 

3197 Format = formats[options.format] 

3198 except KeyError: # pragma: no cover 

3199 argparser.error('invalid format \'%s\'' % options.format) 

3200 

3201 if Format.stdinInput: 

3202 if not args: 

3203 fp = sys.stdin 

3204 parser = Format(fp) 

3205 elif options.compare: 

3206 fp1 = openInput(args[0]) 

3207 fp2 = openInput(args[1]) 

3208 parser1 = Format(fp1) 

3209 parser2 = Format(fp2) 

3210 else: 

3211 fp = openInput(args[0]) 

3212 parser = Format(fp) 

3213 elif Format.multipleInput: 

3214 if not args: # pragma: no cover 

3215 argparser.error('at least a file must be specified for %s input' % options.format) 

3216 if options.compare: 

3217 parser1 = Format(args[-2]) 

3218 parser2 = Format(args[-1]) 

3219 else: 

3220 parser = Format(*args) 

3221 else: 

3222 if len(args) != 1: # pragma: no cover 

3223 argparser.error('exactly one file must be specified for %s input' % options.format) 

3224 parser = Format(args[0]) 

3225 

3226 if options.compare: 

3227 profile1 = parser1.parse() 

3228 profile2 = parser2.parse() 

3229 else: 

3230 profile = parser.parse() 

3231 

3232 if options.output is None: 

3233 output = open(sys.stdout.fileno(), mode='wt', encoding='UTF-8', closefd=False) 

3234 else: 

3235 output = open(options.output, 'wt', encoding='UTF-8') 

3236 

3237 dot = DotWriter(output) 

3238 dot.strip = options.strip 

3239 dot.wrap = options.wrap 

3240 

3241 labelNames = options.node_labels or defaultLabelNames 

3242 dot.show_function_events = [labels[l] for l in labelNames] 

3243 if options.show_samples: 

3244 dot.show_function_events.append(SAMPLES) 

3245 

3246 if options.compare: 

3247 profile1.prune(options.node_thres/100.0, options.edge_thres/100.0, options.filter_paths, 

3248 options.color_nodes_by_selftime) 

3249 profile2.prune(options.node_thres/100.0, options.edge_thres/100.0, options.filter_paths, 

3250 options.color_nodes_by_selftime) 

3251 

3252 if options.root: 

3253 profile1.prune_root(profile1.getFunctionIds(options.root), options.depth) 

3254 profile2.prune_root(profile2.getFunctionIds(options.root), options.depth) 

3255 else: 

3256 profile.prune(options.node_thres/100.0, options.edge_thres/100.0, options.filter_paths, 

3257 options.color_nodes_by_selftime) 

3258 if options.root: 

3259 rootIds = profile.getFunctionIds(options.root) 

3260 if not rootIds: # pragma: no cover 

3261 sys.stderr.write('root node ' + options.root + ' not found (might already be pruned : try -e0 -n0 flags)\n') 

3262 sys.exit(1) 

3263 profile.prune_root(rootIds, options.depth) 

3264 

3265 if options.list_functions: 

3266 profile.printFunctionIds(selector=options.list_functions) 

3267 sys.exit(0) 

3268 

3269 if options.leaf: 

3270 leafIds = profile.getFunctionIds(options.leaf) 

3271 if not leafIds: # pragma: no cover 

3272 sys.stderr.write('leaf node ' + options.leaf + ' not found (maybe already pruned : try -e0 -n0 flags)\n') 

3273 sys.exit(1) 

3274 profile.prune_leaf(leafIds, options.depth) 

3275 

3276 if options.compare: 

3277 dot.graphs_compare(profile1, profile2, theme, options) 

3278 else: 

3279 dot.graph(profile, theme) 

3280 

3281 output.close() 

3282 

3283 

3284if __name__ == '__main__': # pragma: no cover 

3285 main()