paint_cgself.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # paint_cgself.py (round 190tz, used by scripts/paint-callgrind.sh): self cost per (object, function) from a callgrind.out file, plus call counts
  2. import re,sys,collections
  3. def parse(p):
  4. names={}; objs={}; selfc=collections.Counter(); calls=collections.Counter()
  5. ob=fn=None; cfn=None; after_calls=False; fnobj={}
  6. for l in open(p,errors='replace'):
  7. l=l.rstrip('\n')
  8. m=re.match(r'(ob|fl|fi|fe|cob|cfi|cfl)=\((\d+)\)(?: (.*))?$',l)
  9. if m:
  10. k,i,n=m.groups()
  11. if k in('ob','cob'):
  12. if n: objs[i]=n
  13. if k=='ob': ob=objs[i]
  14. continue
  15. m=re.match(r'(c?fn)=\((\d+)\)(?: (.*))?$',l)
  16. if m:
  17. k,i,n=m.groups()
  18. if n: names[i]=n
  19. if k=='fn': fn=names[i]; fnobj[fn]=ob
  20. else: cfn=names[i]
  21. continue
  22. m=re.match(r'calls=(\d+)',l)
  23. if m: calls[cfn]+=int(m.group(1)); after_calls=True; continue
  24. m=re.match(r'^[+-]?(?:\d+|\*|0x[0-9a-f]+)?\s+(\d+)$',l) or re.match(r'^(?:[+-]?\d+|\*)\s+(\d+)$',l)
  25. if m and fn is not None:
  26. if after_calls: after_calls=False
  27. else: selfc[fn]+=int(m.group(1))
  28. return selfc,calls,fnobj
  29. def short(o): o=(o or '???').split('/')[-1]; return 'LYNX' if o.startswith('LYNX') else o
  30. if __name__=='__main__':
  31. a,ca,oa=parse(sys.argv[1]); b,cb,ob=parse(sys.argv[2]); n=int(sys.argv[3]) if len(sys.argv)>3 else 15
  32. agg=collections.defaultdict(lambda:[0,0])
  33. for f,v in a.items(): agg[short(oa.get(f))][0]+=v
  34. for f,v in b.items(): agg[short(ob.get(f))][1]+=v
  35. ta=sum(a.values()); tb=sum(b.values())
  36. print(f"{'object (self cost)':28} {'before':>13} {'after':>13} {'diff':>11}")
  37. for o,(x,y) in sorted(agg.items(),key=lambda r:-r[1][0]):
  38. print(f"{o:28} {x:>13,} {y:>13,} {y-x:+11,} {100*(y-x)/max(1,x):+.3f}%")
  39. print(f"{'TOTAL':28} {ta:>13,} {tb:>13,} {tb-ta:+11,} {100*(tb-ta)/max(1,ta):+.3f}%")
  40. print("top functions by self-cost change:")
  41. rows=sorted(((b.get(f,0)-a.get(f,0),f) for f in set(a)|set(b)),key=lambda r:-abs(r[0]))[:n]
  42. for d,f in rows: print(f" {a.get(f,0):>12,} {b.get(f,0):>12,} {d:+10,} [{short((ob.get(f) or oa.get(f)))}] {f[:110]}")
  43. print("call counts:", ', '.join(f"{k} {ca[k]:,}->{cb[k]:,}" for k in ['malloc','free','realloc','operator new(unsigned long)','pthread_mutex_lock']))
  44. dc=[(cb[k]-ca[k],k) for k in set(ca)|set(cb) if ca[k]!=cb[k] and not k.startswith('0x')]
  45. print("named functions with a different call count:", len(dc), dc[:8])