[ Web Proxy ]
URL:
Viewing:
https://github-redirect.dependabot.com/python/cpython/blob/main/Tools/scripts/summarize_stats.py
[Back]
[Original]
cpython/Tools/scripts/summarize_stats.py at main python/cpython GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
See all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.3k
(2.3k)
Actions
Projects
Security and quality
Insights
More
items
Files
Expand file tree
main
Breadcrumbs
cpython
/
Tools
/
scripts
/
summarize_stats.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
1550 lines (1345 loc) 52 KB
main
Breadcrumbs
cpython
/
Tools
/
scripts
/
summarize_stats.py
Copy path
Top
File metadata and controls
Code
Blame
1550 lines (1345 loc) 52 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Print a summary of specialization stats for all files in the
default stats folders.
"""
from
__future__
import
annotations
# NOTE: Bytecode introspection modules (opcode, dis, etc.) should only
# be imported when loading a single dataset. When comparing datasets, it
# could get it wrong, leading to subtle errors.
import
argparse
import
collections
from
collections
.
abc
import
KeysView
from
dataclasses
import
dataclass
from
datetime
import
date
import
enum
import
functools
import
itertools
import
json
from
operator
import
itemgetter
import
os
from
pathlib
import
Path
import
re
import
sys
import
textwrap
from
typing
import
Any
,
Callable
,
TextIO
,
TypeAlias
RawData
:
TypeAlias
=
dict
[
str
,
Any
]
Rows
:
TypeAlias
=
list
[
tuple
]
Columns
:
TypeAlias
=
tuple
[
str
, ...]
RowCalculator
:
TypeAlias
=
Callable
[[
"Stats"
],
Rows
]
# TODO: Check for parity
if
os
.
name
==
"nt"
:
DEFAULT_DIR
=
"c:
\\
temp
\\
py_stats
\\
"
else
:
DEFAULT_DIR
=
"/tmp/py_stats/"
SOURCE_DIR
=
Path
(
__file__
).
parents
[
2
]
TOTAL
=
"specialization.hit"
,
"specialization.miss"
,
"execution_count"
def
pretty
(
name
:
str
)
->
str
:
return
name
.
replace
(
"_"
,
" "
).
lower
()
def
_load_metadata_from_source
():
def
get_defines
(
filepath
:
Path
,
prefix
:
str
=
"SPEC_FAIL"
):
with
open
(
SOURCE_DIR
/
filepath
)
as
spec_src
:
defines
=
collections
.
defaultdict
(
list
)
start
=
"#define "
+
prefix
+
"_"
for
line
in
spec_src
:
line
=
line
.
strip
()
if
not
line
.
startswith
(
start
):
continue
line
=
line
[
len
(
start
) :]
name
,
val
=
line
.
split
()
defines
[
int
(
val
.
strip
())].
append
(
name
.
strip
())
return
defines
import
opcode
return
{
"_specialized_instructions"
: [
op
for
op
in
opcode
.
_specialized_opmap
.
keys
()
if
"__"
not
in
op
# type: ignore
],
"_stats_defines"
:
get_defines
(
Path
(
"Include"
)
/
"cpython"
/
"pystats.h"
,
"EVAL_CALL"
),
"_defines"
:
get_defines
(
Path
(
"Python"
)
/
"specialize.c"
),
}
def
load_raw_data
(
input
:
Path
)
->
RawData
:
if
input
.
is_file
():
with
open
(
input
,
"r"
)
as
fd
:
data
=
json
.
load
(
fd
)
data
[
"_stats_defines"
]
=
{
int
(
k
):
v
for
k
,
v
in
data
[
"_stats_defines"
].
items
()}
data
[
"_defines"
]
=
{
int
(
k
):
v
for
k
,
v
in
data
[
"_defines"
].
items
()}
return
data
elif
input
.
is_dir
():
stats
=
collections
.
Counter
[
str
]()
for
filename
in
input
.
iterdir
():
with
open
(
filename
)
as
fd
:
for
line
in
fd
:
try
:
key
,
value
=
line
.
split
(
":"
)
except
ValueError
:
print
(
f"Unparsable line: '
{
line
.
strip
()
}
' in
{
filename
}
"
,
file
=
sys
.
stderr
,
)
continue
# Hack to handle older data files where some uops
# are missing an underscore prefix in their name
if
key
.
startswith
(
"uops["
)
and
key
[
5
:
6
]
!=
"_"
:
key
=
"uops[_"
+
key
[
5
:]
stats
[
key
.
strip
()]
+=
int
(
value
)
stats
[
"__nfiles__"
]
+=
1
data
=
dict
(
stats
)
data
.
update
(
_load_metadata_from_source
())
return
data
else
:
raise
ValueError
(
f"
{
input
}
is not a file or directory path"
)
def
save_raw_data
(
data
:
RawData
,
json_output
:
TextIO
):
json
.
dump
(
data
,
json_output
)
@
dataclass
(
frozen
=
True
)
class
Doc
:
text
:
str
doc
:
str
def
markdown
(
self
)
->
str
:
return
textwrap
.
dedent
(
f"""
{
self
.
text
}
<details>
<summary></summary>
{
self
.
doc
}
</details>
"""
)
class
Count
(
int
):
def
markdown
(
self
)
->
str
:
return
format
(
self
,
",d"
)
@
dataclass
(
frozen
=
True
)
class
Ratio
:
num
:
int
den
:
int
|
None
=
None
percentage
:
bool
=
True
def
__float__
(
self
):
if
self
.
den
==
0
:
return
0.0
elif
self
.
den
is
None
:
return
self
.
num
else
:
return
self
.
num
/
self
.
den
def
markdown
(
self
)
->
str
:
if
self
.
den
is
None
:
return
""
elif
self
.
den
==
0
:
if
self
.
num
!=
0
:
return
f"
{
self
.
num
:,
}
/ 0 !!"
return
""
elif
self
.
percentage
:
return
f"
{
self
.
num
/
self
.
den
:,.01%
}
"
else
:
return
f"
{
self
.
num
/
self
.
den
:,.02f
}
"
class
DiffRatio
(
Ratio
):
def
__init__
(
self
,
base
:
int
|
str
,
head
:
int
|
str
):
if
isinstance
(
base
,
str
)
or
isinstance
(
head
,
str
):
super
().
__init__
(
0
,
0
)
else
:
super
().
__init__
(
head
-
base
,
base
)
class
OpcodeStats
:
"""
Manages the data related to specific set of opcodes, e.g. tier1 (with prefix
"opcode") or tier2 (with prefix "uops").
"""
def
__init__
(
self
,
data
:
dict
[
str
,
Any
],
defines
,
specialized_instructions
):
self
.
_data
=
data
self
.
_defines
=
defines
self
.
_specialized_instructions
=
specialized_instructions
def
get_opcode_names
(
self
)
->
KeysView
[
str
]:
return
self
.
_data
.
keys
()
def
get_pair_counts
(
self
)
->
dict
[
tuple
[
str
,
str
],
int
]:
pair_counts
=
{}
for
name_i
,
opcode_stat
in
self
.
_data
.
items
():
for
key
,
value
in
opcode_stat
.
items
():
if
value
and
key
.
startswith
(
"pair_count"
):
name_j
,
_
,
_
=
key
[
len
(
"pair_count"
)
+
1
:].
partition
(
"]"
)
pair_counts
[(
name_i
,
name_j
)]
=
value
return
pair_counts
def
get_total_execution_count
(
self
)
->
int
:
return
sum
(
x
.
get
(
"execution_count"
,
0
)
for
x
in
self
.
_data
.
values
())
def
get_execution_counts
(
self
)
->
dict
[
str
,
tuple
[
int
,
int
]]:
counts
=
{}
for
name
,
opcode_stat
in
self
.
_data
.
items
():
if
"execution_count"
in
opcode_stat
:
count
=
opcode_stat
[
"execution_count"
]
miss
=
0
if
"specializable"
not
in
opcode_stat
:
miss
=
opcode_stat
.
get
(
"specialization.miss"
,
0
)
counts
[
name
]
=
(
count
,
miss
)
return
counts
@
functools
.
cache
def
_get_pred_succ
(
self
,
)
->
tuple
[
dict
[
str
,
collections
.
Counter
],
dict
[
str
,
collections
.
Counter
]]:
pair_counts
=
self
.
get_pair_counts
()
predecessors
:
dict
[
str
,
collections
.
Counter
]
=
collections
.
defaultdict
(
collections
.
Counter
)
successors
:
dict
[
str
,
collections
.
Counter
]
=
collections
.
defaultdict
(
collections
.
Counter
)
for
(
first
,
second
),
count
in
pair_counts
.
items
():
if
count
:
predecessors
[
second
][
first
]
=
count
successors
[
first
][
second
]
=
count
return
predecessors
,
successors
def
get_predecessors
(
self
,
opcode
:
str
)
->
collections
.
Counter
[
str
]:
return
self
.
_get_pred_succ
()[
0
][
opcode
]
def
get_successors
(
self
,
opcode
:
str
)
->
collections
.
Counter
[
str
]:
return
self
.
_get_pred_succ
()[
1
][
opcode
]
def
_get_stats_for_opcode
(
self
,
opcode
:
str
)
->
dict
[
str
,
int
]:
return
self
.
_data
[
opcode
]
def
get_specialization_total
(
self
,
opcode
:
str
)
->
int
:
family_stats
=
self
.
_get_stats_for_opcode
(
opcode
)
return
sum
(
family_stats
.
get
(
kind
,
0
)
for
kind
in
TOTAL
)
def
get_specialization_counts
(
self
,
opcode
:
str
)
->
dict
[
str
,
int
]:
family_stats
=
self
.
_get_stats_for_opcode
(
opcode
)
result
=
{}
for
key
,
value
in
sorted
(
family_stats
.
items
()):
if
key
.
startswith
(
"specialization."
):
label
=
key
[
len
(
"specialization."
) :]
if
label
in
(
"success"
,
"failure"
)
or
label
.
startswith
(
"failure_kinds"
):
continue
elif
key
in
(
"execution_count"
,
"specializable"
,
)
or
key
.
startswith
(
"pair"
):
continue
else
:
label
=
key
result
[
label
]
=
value
return
result
def
get_specialization_success_failure
(
self
,
opcode
:
str
)
->
dict
[
str
,
int
]:
family_stats
=
self
.
_get_stats_for_opcode
(
opcode
)
result
=
{}
for
key
in
(
"specialization.success"
,
"specialization.failure"
):
label
=
key
[
len
(
"specialization."
) :]
val
=
family_stats
.
get
(
key
,
0
)
result
[
label
]
=
val
return
result
def
get_specialization_failure_total
(
self
,
opcode
:
str
)
->
int
:
return
self
.
_get_stats_for_opcode
(
opcode
).
get
(
"specialization.failure"
,
0
)
def
get_specialization_failure_kinds
(
self
,
opcode
:
str
)
->
dict
[
str
,
int
]:
def
kind_to_text
(
kind
:
int
,
opcode
:
str
):
if
kind
<=
8
:
return
pretty
(
self
.
_defines
[
kind
][
0
])
if
opcode
==
"LOAD_SUPER_ATTR"
:
opcode
=
"SUPER"
elif
opcode
.
endswith
(
"ATTR"
):
opcode
=
"ATTR"
elif
opcode
in
(
"FOR_ITER"
,
"GET_ITER"
,
"SEND"
):
opcode
=
"ITER"
elif
opcode
.
endswith
(
"SUBSCR"
):
opcode
=
"SUBSCR"
for
name
in
self
.
_defines
[
kind
]:
if
name
.
startswith
(
opcode
):
return
pretty
(
name
[
len
(
opcode
)
+
1
:])
return
"kind "
+
str
(
kind
)
family_stats
=
self
.
_get_stats_for_opcode
(
opcode
)
def
key_to_index
(
key
):
return
int
(
key
[:
-
1
].
split
(
"["
)[
1
])
max_index
=
0
for
key
in
family_stats
:
if
key
.
startswith
(
"specialization.failure_kind"
):
max_index
=
max
(
max_index
,
key_to_index
(
key
))
failure_kinds
=
[
0
]
*
(
max_index
+
1
)
for
key
in
family_stats
:
if
not
key
.
startswith
(
"specialization.failure_kind"
):
continue
failure_kinds
[
key_to_index
(
key
)]
=
family_stats
[
key
]
return
{
kind_to_text
(
index
,
opcode
):
value
for
(
index
,
value
)
in
enumerate
(
failure_kinds
)
if
value
}
def
is_specializable
(
self
,
opcode
:
str
)
->
bool
:
return
"specializable"
in
self
.
_get_stats_for_opcode
(
opcode
)
def
get_specialized_total_counts
(
self
)
->
tuple
[
int
,
int
,
int
]:
basic
=
0
specialized_hits
=
0
specialized_misses
=
0
not_specialized
=
0
for
opcode
,
opcode_stat
in
self
.
_data
.
items
():
if
"execution_count"
not
in
opcode_stat
:
continue
count
=
opcode_stat
[
"execution_count"
]
if
"specializable"
in
opcode_stat
:
not_specialized
+=
count
elif
opcode
in
self
.
_specialized_instructions
:
miss
=
opcode_stat
.
get
(
"specialization.miss"
,
0
)
specialized_hits
+=
count
-
miss
specialized_misses
+=
miss
else
:
basic
+=
count
return
basic
,
specialized_hits
,
specialized_misses
,
not_specialized
def
get_deferred_counts
(
self
)
->
dict
[
str
,
int
]:
return
{
opcode
:
opcode_stat
.
get
(
"specialization.deferred"
,
0
)
for
opcode
,
opcode_stat
in
self
.
_data
.
items
()
if
opcode
!=
"RESUME"
}
def
get_misses_counts
(
self
)
->
dict
[
str
,
int
]:
return
{
opcode
:
opcode_stat
.
get
(
"specialization.miss"
,
0
)
for
opcode
,
opcode_stat
in
self
.
_data
.
items
()
if
not
self
.
is_specializable
(
opcode
)
}
def
get_opcode_counts
(
self
)
->
dict
[
str
,
int
]:
counts
=
{}
for
opcode
,
entry
in
self
.
_data
.
items
():
count
=
entry
.
get
(
"count"
,
0
)
if
count
:
counts
[
opcode
]
=
count
return
counts
class
Stats
:
def
__init__
(
self
,
data
:
RawData
):
self
.
_data
=
data
def
get
(
self
,
key
:
str
)
->
int
:
return
self
.
_data
.
get
(
key
,
0
)
@
functools
.
cache
def
get_opcode_stats
(
self
,
prefix
:
str
)
->
OpcodeStats
:
opcode_stats
=
collections
.
defaultdict
[
str
,
dict
](
dict
)
for
key
,
value
in
self
.
_data
.
items
():
if
not
key
.
startswith
(
prefix
):
continue
name
,
_
,
rest
=
key
[
len
(
prefix
)
+
1
:].
partition
(
"]"
)
opcode_stats
[
name
][
rest
.
strip
(
"."
)]
=
value
return
OpcodeStats
(
opcode_stats
,
self
.
_data
[
"_defines"
],
self
.
_data
[
"_specialized_instructions"
],
)
def
get_call_stats
(
self
)
->
dict
[
str
,
int
]:
defines
=
self
.
_data
[
"_stats_defines"
]
result
=
{}
for
key
,
value
in
sorted
(
self
.
_data
.
items
()):
if
"Calls to"
in
key
:
result
[
key
]
=
value
elif
key
.
startswith
(
"Calls "
):
name
,
index
=
key
[:
-
1
].
split
(
"["
)
label
=
f"
{
name
}
(
{
pretty
(
defines
[
int
(
index
)][
0
])
}
)"
result
[
label
]
=
value
for
key
,
value
in
sorted
(
self
.
_data
.
items
()):
if
key
.
startswith
(
"Frame"
):
result
[
key
]
=
value
return
result
def
get_object_stats
(
self
)
->
dict
[
str
,
tuple
[
int
,
int
]]:
total_materializations
=
self
.
_data
.
get
(
"Object inline values"
,
0
)
total_allocations
=
self
.
_data
.
get
(
"Object allocations"
,
0
)
+
self
.
_data
.
get
(
"Object allocations from freelist"
,
0
)
total_increfs
=
(
self
.
_data
.
get
(
"Object interpreter mortal increfs"
,
0
)
+
self
.
_data
.
get
(
"Object mortal increfs"
,
0
)
+
self
.
_data
.
get
(
"Object interpreter immortal increfs"
,
0
)
+
self
.
_data
.
get
(
"Object immortal increfs"
,
0
)
)
total_decrefs
=
(
self
.
_data
.
get
(
"Object interpreter mortal decrefs"
,
0
)
+
self
.
_data
.
get
(
"Object mortal decrefs"
,
0
)
+
self
.
_data
.
get
(
"Object interpreter immortal decrefs"
,
0
)
+
self
.
_data
.
get
(
"Object immortal decrefs"
,
0
)
)
result
=
{}
for
key
,
value
in
self
.
_data
.
items
():
if
key
.
startswith
(
"Object"
):
if
"materialize"
in
key
:
den
=
total_materializations
elif
"allocations"
in
key
:
den
=
total_allocations
elif
"increfs"
in
key
:
den
=
total_increfs
elif
"decrefs"
in
key
:
den
=
total_decrefs
else
:
den
=
None
label
=
key
[
6
:].
strip
()
label
=
label
[
0
].
upper
()
+
label
[
1
:]
result
[
label
]
=
(
value
,
den
)
return
result
def
get_gc_stats
(
self
)
->
list
[
dict
[
str
,
int
]]:
gc_stats
:
list
[
dict
[
str
,
int
]]
=
[]
for
key
,
value
in
self
.
_data
.
items
():
if
not
key
.
startswith
(
"GC"
):
continue
n
,
_
,
rest
=
key
[
3
:].
partition
(
"]"
)
name
=
rest
.
strip
()
gen_n
=
int
(
n
)
while
len
(
gc_stats
)
<=
gen_n
:
gc_stats
.
append
({})
gc_stats
[
gen_n
][
name
]
=
value
return
gc_stats
def
get_optimization_stats
(
self
)
->
dict
[
str
,
tuple
[
int
,
int
|
None
]]:
if
"Optimization attempts"
not
in
self
.
_data
:
return
{}
attempts
=
self
.
_data
[
"Optimization attempts"
]
created
=
self
.
_data
[
"Optimization traces created"
]
executed
=
self
.
_data
[
"Optimization traces executed"
]
uops
=
self
.
_data
[
"Optimization uops executed"
]
trace_stack_overflow
=
self
.
_data
[
"Optimization trace stack overflow"
]
trace_stack_underflow
=
self
.
_data
[
"Optimization trace stack underflow"
]
trace_too_long
=
self
.
_data
[
"Optimization trace too long"
]
trace_too_short
=
self
.
_data
[
"Optimization trace too short"
]
inner_loop
=
self
.
_data
[
"Optimization inner loop"
]
recursive_call
=
self
.
_data
[
"Optimization recursive call"
]
low_confidence
=
self
.
_data
[
"Optimization low confidence"
]
unknown_callee
=
self
.
_data
[
"Optimization unknown callee"
]
executors_invalidated
=
self
.
_data
[
"Executors invalidated"
]
return
{
Doc
(
"Optimization attempts"
,
"The number of times a potential trace is identified. Specifically, this "
"occurs in the JUMP BACKWARD instruction when the counter reaches a "
"threshold."
,
): (
attempts
,
None
),
Doc
(
"Traces created"
,
"The number of traces that were successfully created."
): (
created
,
attempts
),
Doc
(
"Trace stack overflow"
,
"A trace is truncated because it would require more than 5 stack frames."
,
): (
trace_stack_overflow
,
attempts
),
Doc
(
"Trace stack underflow"
,
"A potential trace is abandoned because it pops more frames than it pushes."
,
): (
trace_stack_underflow
,
attempts
),
Doc
(
"Trace too long"
,
"A trace is truncated because it is longer than the instruction buffer."
,
): (
trace_too_long
,
attempts
),
Doc
(
"Trace too short"
,
"A potential trace is abandoned because it is too short."
,
): (
trace_too_short
,
attempts
),
Doc
(
"Inner loop found"
,
"A trace is truncated because it has an inner loop"
): (
inner_loop
,
attempts
),
Doc
(
"Recursive call"
,
"A trace is truncated because it has a recursive call."
,
): (
recursive_call
,
attempts
),
Doc
(
"Low confidence"
,
"A trace is abandoned because the likelihood of the jump to top being taken "
"is too low."
,
): (
low_confidence
,
attempts
),
Doc
(
"Unknown callee"
,
"A trace is abandoned because the target of a call is unknown."
,
): (
unknown_callee
,
attempts
),
Doc
(
"Executors invalidated"
,
"The number of executors that were invalidated due to watched "
"dictionary changes."
,
): (
executors_invalidated
,
created
),
Doc
(
"Traces executed"
,
"The number of traces that were executed"
): (
executed
,
None
,
),
Doc
(
"Uops executed"
,
"The total number of uops (micro-operations) that were executed"
,
): (
uops
,
executed
,
),
}
def
get_optimizer_stats
(
self
)
->
dict
[
str
,
tuple
[
int
,
int
|
None
]]:
attempts
=
self
.
_data
[
"Optimization optimizer attempts"
]
successes
=
self
.
_data
[
"Optimization optimizer successes"
]
no_memory
=
self
.
_data
[
"Optimization optimizer failure no memory"
]
builtins_changed
=
self
.
_data
[
"Optimizer remove globals builtins changed"
]
incorrect_keys
=
self
.
_data
[
"Optimizer remove globals incorrect keys"
]
return
{
Doc
(
"Optimizer attempts"
,
"The number of times the trace optimizer (_Py_uop_analyze_and_optimize) was run."
,
): (
attempts
,
None
),
Doc
(
"Optimizer successes"
,
"The number of traces that were successfully optimized."
,
): (
successes
,
attempts
),
Doc
(
"Optimizer no memory"
,
"The number of optimizations that failed due to no memory."
,
): (
no_memory
,
attempts
),
Doc
(
"Remove globals builtins changed"
,
"The builtins changed during optimization"
,
): (
builtins_changed
,
attempts
),
Doc
(
"Remove globals incorrect keys"
,
"The keys in the globals dictionary aren't what was expected"
,
): (
incorrect_keys
,
attempts
),
}
def
get_jit_memory_stats
(
self
)
->
dict
[
Doc
,
tuple
[
int
,
int
|
None
]]:
jit_total_memory_size
=
self
.
_data
[
"JIT total memory size"
]
jit_code_size
=
self
.
_data
[
"JIT code size"
]
jit_trampoline_size
=
self
.
_data
[
"JIT trampoline size"
]
jit_data_size
=
self
.
_data
[
"JIT data size"
]
jit_padding_size
=
self
.
_data
[
"JIT padding size"
]
jit_freed_memory_size
=
self
.
_data
[
"JIT freed memory size"
]
return
{
Doc
(
"Total memory size"
,
"The total size of the memory allocated for the JIT traces"
,
): (
jit_total_memory_size
,
None
),
Doc
(
"Code size"
,
"The size of the memory allocated for the code of the JIT traces"
,
): (
jit_code_size
,
jit_total_memory_size
),
Doc
(
"Trampoline size"
,
"The size of the memory allocated for the trampolines of the JIT traces"
,
): (
jit_trampoline_size
,
jit_total_memory_size
),
Doc
(
"Data size"
,
"The size of the memory allocated for the data of the JIT traces"
,
): (
jit_data_size
,
jit_total_memory_size
),
Doc
(
"Padding size"
,
"The size of the memory allocated for the padding of the JIT traces"
,
): (
jit_padding_size
,
jit_total_memory_size
),
Doc
(
"Freed memory size"
,
"The size of the memory freed from the JIT traces"
,
): (
jit_freed_memory_size
,
jit_total_memory_size
),
}
def
get_histogram
(
self
,
prefix
:
str
)
->
list
[
tuple
[
int
,
int
]]:
rows
=
[]
for
k
,
v
in
self
.
_data
.
items
():
match
=
re
.
match
(
f"
{
prefix
}
\\
[([0-9]+)
\\
]"
,
k
)
if
match
is
not
None
:
entry
=
int
(
match
.
groups
()[
0
])
rows
.
append
((
entry
,
v
))
rows
.
sort
()
return
rows
def
get_rare_events
(
self
)
->
list
[
tuple
[
str
,
int
]]:
prefix
=
"Rare event "
return
[
(
key
[
len
(
prefix
)
+
1
:
-
1
].
replace
(
"_"
,
" "
),
val
)
for
key
,
val
in
self
.
_data
.
items
()
if
key
.
startswith
(
prefix
)
]
class
JoinMode
(
enum
.
Enum
):
# Join using the first column as a key
SIMPLE
=
0
# Join using the first column as a key, and indicate the change in the
# second column of each input table as a new column
CHANGE
=
1
# Join using the first column as a key, indicating the change in the second
# column of each input table as a new column, and omit all other columns
CHANGE_ONE_COLUMN
=
2
# Join using the first column as a key, and indicate the change as a new
# column, but don't sort by the amount of change.
CHANGE_NO_SORT
=
3
class
Table
:
"""
A Table defines how to convert a set of Stats into a specific set of rows
displaying some aspect of the data.
"""
def
__init__
(
self
,
column_names
:
Columns
,
calc_rows
:
RowCalculator
,
join_mode
:
JoinMode
=
JoinMode
.
SIMPLE
,
):
self
.
columns
=
column_names
self
.
calc_rows
=
calc_rows
self
.
join_mode
=
join_mode
def
join_row
(
self
,
key
:
str
,
row_a
:
tuple
,
row_b
:
tuple
)
->
tuple
:
match
self
.
join_mode
:
case
JoinMode
.
SIMPLE
:
return
(
key
,
*
row_a
,
*
row_b
)
case
JoinMode
.
CHANGE
|
JoinMode
.
CHANGE_NO_SORT
:
return
(
key
,
*
row_a
,
*
row_b
,
DiffRatio
(
row_a
[
0
],
row_b
[
0
]))
case
JoinMode
.
CHANGE_ONE_COLUMN
:
return
(
key
,
row_a
[
0
],
row_b
[
0
],
DiffRatio
(
row_a
[
0
],
row_b
[
0
]))
def
join_columns
(
self
,
columns
:
Columns
)
->
Columns
:
match
self
.
join_mode
:
case
JoinMode
.
SIMPLE
:
return
(
columns
[
0
],
*
(
"Base "
+
x
for
x
in
columns
[
1
:]),
*
(
"Head "
+
x
for
x
in
columns
[
1
:]),
)
case
JoinMode
.
CHANGE
|
JoinMode
.
CHANGE_NO_SORT
:
return
(
columns
[
0
],
*
(
"Base "
+
x
for
x
in
columns
[
1
:]),
*
(
"Head "
+
x
for
x
in
columns
[
1
:]),
)
+
(
"Change:"
,)
case
JoinMode
.
CHANGE_ONE_COLUMN
:
return
(
columns
[
0
],
"Base "
+
columns
[
1
],
"Head "
+
columns
[
1
],
"Change:"
,
)
def
join_tables
(
self
,
rows_a
:
Rows
,
rows_b
:
Rows
)
->
tuple
[
Columns
,
Rows
]:
ncols
=
len
(
self
.
columns
)
default
=
(
""
,)
*
(
ncols
-
1
)
data_a
=
{
x
[
0
]:
x
[
1
:]
for
x
in
rows_a
}
data_b
=
{
x
[
0
]:
x
[
1
:]
for
x
in
rows_b
}
if
len
(
data_a
)
!=
len
(
rows_a
)
or
len
(
data_b
)
!=
len
(
rows_b
):
raise
ValueError
(
"Duplicate keys"
)
# To preserve ordering, use A's keys as is and then add any in B that
# aren't in A
keys
=
list
(
data_a
.
keys
())
+
[
k
for
k
in
data_b
.
keys
()
if
k
not
in
data_a
]
rows
=
[
self
.
join_row
(
k
,
data_a
.
get
(
k
,
default
),
data_b
.
get
(
k
,
default
))
for
k
in
keys
]
if
self
.
join_mode
in
(
JoinMode
.
CHANGE
,
JoinMode
.
CHANGE_ONE_COLUMN
):
rows
.
sort
(
key
=
lambda
row
:
abs
(
float
(
row
[
-
1
])),
reverse
=
True
)
columns
=
self
.
join_columns
(
self
.
columns
)
return
columns
,
rows
def
get_table
(
self
,
base_stats
:
Stats
,
head_stats
:
Stats
|
None
=
None
)
->
tuple
[
Columns
,
Rows
]:
if
head_stats
is
None
:
rows
=
self
.
calc_rows
(
base_stats
)
return
self
.
columns
,
rows
else
:
rows_a
=
self
.
calc_rows
(
base_stats
)
rows_b
=
self
.
calc_rows
(
head_stats
)
cols
,
rows
=
self
.
join_tables
(
rows_a
,
rows_b
)
return
cols
,
rows
class
Section
:
"""
A Section defines a section of the output document.
"""
def
__init__
(
self
,
title
:
str
=
""
,
summary
:
str
=
""
,
part_iter
=
None
,
*
,
comparative
:
bool
=
True
,
doc
:
str
=
""
,
):
self
.
title
=
title
if
not
summary
:
self
.
summary
=
title
.
lower
()
else
:
self
.
summary
=
summary
self
.
doc
=
textwrap
.
dedent
(
doc
)
if
part_iter
is
None
:
part_iter
=
[]
if
isinstance
(
part_iter
,
list
):
def
iter_parts
(
base_stats
:
Stats
,
head_stats
:
Stats
|
None
):
yield
from
part_iter
self
.
part_iter
=
iter_parts
else
:
self
.
part_iter
=
part_iter
self
.
comparative
=
comparative
def
calc_execution_count_table
(
prefix
:
str
)
->
RowCalculator
:
def
calc
(
stats
:
Stats
)
->
Rows
:
opcode_stats
=
stats
.
get_opcode_stats
(
prefix
)
counts
=
opcode_stats
.
get_execution_counts
()
total
=
opcode_stats
.
get_total_execution_count
()
cumulative
=
0
rows
:
Rows
=
[]
for
opcode
, (
count
,
miss
)
in
sorted
(
counts
.
items
(),
key
=
itemgetter
(
1
),
reverse
=
True
):
cumulative
+=
count
if
miss
:
miss_val
=
Ratio
(
miss
,
count
)
else
:
miss_val
=
None
rows
.
append
(
(
opcode
,
Count
(
count
),
Ratio
(
count
,
total
),
Ratio
(
cumulative
,
total
),
miss_val
,
)
)
return
rows
return
calc
def
execution_count_section
()
->
Section
:
return
Section
(
"Execution counts"
,
"Execution counts for Tier 1 instructions."
,
[
Table
(
(
"Name"
,
"Count:"
,
"Self:"
,
"Cumulative:"
,
"Miss ratio:"
),
calc_execution_count_table
(
"opcode"
),
join_mode
=
JoinMode
.
CHANGE_ONE_COLUMN
,
)
],
doc
=
"""
The "miss ratio" column shows the percentage of times the instruction
executed that it deoptimized. When this happens, the base unspecialized
instruction is not counted.
"""
,
)
def
pair_count_section
(
prefix
:
str
,
title
=
None
)
->
Section
:
def
calc_pair_count_table
(
stats
:
Stats
)
->
Rows
:
opcode_stats
=
stats
.
get_opcode_stats
(
prefix
)
pair_counts
=
opcode_stats
.
get_pair_counts
()
total
=
opcode_stats
.
get_total_execution_count
()
cumulative
=
0
rows
:
Rows
=
[]
for
(
opcode_i
,
opcode_j
),
count
in
itertools
.
islice
(
sorted
(
pair_counts
.
items
(),
key
=
itemgetter
(
1
),
reverse
=
True
),
100
):
cumulative
+=
count
rows
.
append
(
(
f"
{
opcode_i
}
{
opcode_j
}
"
,
Count
(
count
),
Ratio
(
count
,
total
),
Ratio
(
cumulative
,
total
),
)
)
return
rows
return
Section
(
"Pair counts"
,
f"Pair counts for top 100
{
title
if
title
else
prefix
}
pairs"
,
[
Table
(
(
"Pair"
,
"Count:"
,
"Self:"
,
"Cumulative:"
),
calc_pair_count_table
,
)
],
comparative
=
False
,
doc
=
"""
Pairs of specialized operations that deoptimize and are then followed by
the corresponding unspecialized instruction are not counted as pairs.
"""
,
)
def
pre_succ_pairs_section
()
->
Section
:
def
iter_pre_succ_pairs_tables
(
base_stats
:
Stats
,
head_stats
:
Stats
|
None
=
None
):
assert
head_stats
is
None
opcode_stats
=
base_stats
.
get_opcode_stats
(
"opcode"
)
for
opcode
in
opcode_stats
.
get_opcode_names
():
predecessors
=
opcode_stats
.
get_predecessors
(
opcode
)
successors
=
opcode_stats
.
get_successors
(
opcode
)
predecessors_total
=
predecessors
.
total
()
successors_total
=
successors
.
total
()
if
predecessors_total
==
0
and
successors_total
==
0
:
continue
pred_rows
=
[
(
pred
,
Count
(
count
),
Ratio
(
count
,
predecessors_total
))
for
(
pred
,
count
)
in
predecessors
.
most_common
(
5
)
]
succ_rows
=
[
(
succ
,
Count
(
count
),
Ratio
(
count
,
successors_total
))
for
(
succ
,
count
)
in
successors
.
most_common
(
5
)
]
yield
Section
(
opcode
,
f"Successors and predecessors for
{
opcode
}
"
,
[
Table
(
(
"Predecessors"
,
"Count:"
,
"Percentage:"
),
lambda
*
_
:
pred_rows
,
# type: ignore
),
Table
(
(
"Successors"
,
"Count:"
,
"Percentage:"
),
lambda
*
_
:
succ_rows
,
# type: ignore
),
],
)
return
Section
(
"Predecessor/Successor Pairs"
,
"Top 5 predecessors and successors of each Tier 1 opcode."
,
iter_pre_succ_pairs_tables
,
comparative
=
False
,
doc
=
"""
This does not include the unspecialized instructions that occur after a
specialized instruction deoptimizes.
"""
,
)
def
specialization_section
()
->
Section
:
def
calc_specialization_table
(
opcode
:
str
)
->
RowCalculator
:
def
calc
(
stats
:
Stats
)
->
Rows
:
DOCS
=
{
"deferred"
:
'Lists the number of "deferred" (i.e. not specialized) instructions executed.'
,
"hit"
:
"Specialized instructions that complete."
,
"miss"
:
"Specialized instructions that deopt."
,
"deopt"
:
"Specialized instructions that deopt."
,
}
opcode_stats
=
stats
.
get_opcode_stats
(
"opcode"
)
total
=
opcode_stats
.
get_specialization_total
(
opcode
)
specialization_counts
=
opcode_stats
.
get_specialization_counts
(
opcode
)
return
[
(
Doc
(
label
,
DOCS
[
label
]),
Count
(
count
),
Ratio
(
count
,
total
),
)
for
label
,
count
in
specialization_counts
.
items
()
]
return
calc
def
calc_specialization_success_failure_table
(
name
:
str
)
->
RowCalculator
:
def
calc
(
stats
:
Stats
)
->
Rows
:
values
=
stats
.
get_opcode_stats
(
"opcode"
).
get_specialization_success_failure
(
name
)
total
=
sum
(
values
.
values
())
if
total
:
return
[
(
label
.
capitalize
(),
Count
(
val
),
Ratio
(
val
,
total
))
for
label
,
val
in
values
.
items
()
]
else
:
return
[]
return
calc
def
calc_specialization_failure_kind_table
(
name
:
str
)
->
RowCalculator
:
def
calc
(
stats
:
Stats
)
->
Rows
:
opcode_stats
=
stats
.
get_opcode_stats
(
"opcode"
)
failures
=
opcode_stats
.
get_specialization_failure_kinds
(
name
)
total
=
opcode_stats
.
get_specialization_failure_total
(
name
)
return
sorted
(
[
(
label
,
Count
(
value
),
Ratio
(
value
,
total
))
for
label
,
value
in
failures
.
items
()
if
value
],
key
=
itemgetter
(
1
),
reverse
=
True
,
)
return
calc
def
iter_specialization_tables
(
base_stats
:
Stats
,
head_stats
:
Stats
|
None
=
None
):
opcode_base_stats
=
base_stats
.
get_opcode_stats
(
"opcode"
)
names
=
opcode_base_stats
.
get_opcode_names
()
if
head_stats
is
not
None
:
opcode_head_stats
=
head_stats
.
get_opcode_stats
(
"opcode"
)
names
&=
opcode_head_stats
.
get_opcode_names
()
# type: ignore
else
:
opcode_head_stats
=
None
for
opcode
in
sorted
(
names
):
if
not
opcode_base_stats
.
is_specializable
(
opcode
):
continue
if
opcode_base_stats
.
get_specialization_total
(
opcode
)
==
0
and
(
opcode_head_stats
is
None
or
opcode_head_stats
.
get_specialization_total
(
opcode
)
==
0
):
continue
yield
Section
(
opcode
,
f"specialization stats for
{
opcode
}
family"
,
[
Table
(
(
"Kind"
,
"Count:"
,
"Ratio:"
),
calc_specialization_table
(
opcode
),
JoinMode
.
CHANGE
,
),
Table
(
(
"Success"
,
"Count:"
,
"Ratio:"
),
calc_specialization_success_failure_table
(
opcode
),
JoinMode
.
CHANGE
,
),
Table
(
(
"Failure kind"
,
"Count:"
,
"Ratio:"
),
calc_specialization_failure_kind_table
(
opcode
),
JoinMode
.
CHANGE
,
),
],
)
return
Section
(
"Specialization stats"
,
"Specialization stats by family"
,
iter_specialization_tables
,
)
def
specialization_effectiveness_section
()
->
Section
:
def
calc_specialization_effectiveness_table
(
stats
:
Stats
)
->
Rows
:
opcode_stats
=
stats
.
get_opcode_stats
(
"opcode"
)
total
=
opcode_stats
.
get_total_execution_count
()
(
basic
,
specialized_hits
,
specialized_misses
,
not_specialized
,
)
=
opcode_stats
.
get_specialized_total_counts
()
return
[
(
Doc
(
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
Manage cookies
Do not share my personal information
You cant perform that action at this time.
Web Proxy Viewer |
New URL
|
Original Page