-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathyappi.py
1519 lines (1247 loc) · 45.2 KB
/
yappi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
"""
yappi.py - Yet Another Python Profiler
"""
import os
import sys
import _yappi
import pickle
import threading
import warnings
import types
import inspect
import itertools
try:
from thread import get_ident # Python 2
except ImportError:
from threading import get_ident # Python 3
from contextlib import contextmanager
class YappiError(Exception):
pass
__all__ = [
'start', 'stop', 'get_func_stats', 'get_thread_stats', 'clear_stats',
'is_running', 'get_clock_time', 'get_clock_type', 'set_clock_type',
'get_clock_info', 'get_mem_usage', 'set_context_backend'
]
LINESEP = os.linesep
COLUMN_GAP = 2
YPICKLE_PROTOCOL = 2
# this dict holds {full_name: code object or PyCfunctionobject}. We did not hold
# this in YStat because it makes it unpickable. I played with some code to make it
# unpickable by NULLifying the fn_descriptor attrib. but there were lots of happening
# and some multithread tests were failing, I switched back to a simpler design:
# do not hold fn_descriptor inside YStats. This is also better design since YFuncStats
# will have this value only optionally because of unpickling problems of CodeObjects.
_fn_descriptor_dict = {}
COLUMNS_FUNCSTATS = ["name", "ncall", "ttot", "tsub", "tavg"]
SORT_TYPES_FUNCSTATS = {
"name": 0,
"callcount": 3,
"totaltime": 6,
"subtime": 7,
"avgtime": 14,
"ncall": 3,
"ttot": 6,
"tsub": 7,
"tavg": 14
}
SORT_TYPES_CHILDFUNCSTATS = {
"name": 10,
"callcount": 1,
"totaltime": 3,
"subtime": 4,
"avgtime": 5,
"ncall": 1,
"ttot": 3,
"tsub": 4,
"tavg": 5
}
SORT_ORDERS = {"ascending": 0, "asc": 0, "descending": 1, "desc": 1}
DEFAULT_SORT_TYPE = "totaltime"
DEFAULT_SORT_ORDER = "desc"
CLOCK_TYPES = {"WALL": 0, "CPU": 1}
NATIVE_THREAD = "NATIVE_THREAD"
GREENLET = "GREENLET"
BACKEND_TYPES = {NATIVE_THREAD: 0, GREENLET: 1}
try:
GREENLET_COUNTER = itertools.count(start=1).next
except AttributeError:
GREENLET_COUNTER = itertools.count(start=1).__next__
def _validate_sorttype(sort_type, list):
sort_type = sort_type.lower()
if sort_type not in list:
raise YappiError(f"Invalid SortType parameter: '{sort_type}'")
return sort_type
def _validate_sortorder(sort_order):
sort_order = sort_order.lower()
if sort_order not in SORT_ORDERS:
raise YappiError(f"Invalid SortOrder parameter: '{sort_order}'")
return sort_order
def _validate_columns(name, list):
name = name.lower()
if name not in list:
raise YappiError(f"Invalid Column name: '{name}'")
def _ctx_name_callback():
"""
We don't use threading.current_thread() because it will deadlock if
called when profiling threading._active_limbo_lock.acquire().
See: #Issue48.
"""
try:
current_thread = threading._active[get_ident()]
return current_thread.__class__.__name__
except KeyError:
# Threads may not be registered yet in first few profile callbacks.
return None
def _profile_thread_callback(frame, event, arg):
"""
_profile_thread_callback will only be called once per-thread. _yappi will detect
the new thread and changes the profilefunc param of the ThreadState
structure. This is an internal function please don't mess with it.
"""
_yappi._profile_event(frame, event, arg)
def _create_greenlet_callbacks():
"""
Returns two functions:
- one that can identify unique greenlets. Identity of a greenlet
cannot be reused once a greenlet dies. 'id(greenlet)' cannot be used because
'id' returns an identifier that can be reused once a greenlet object is garbage
collected.
- one that can return the name of the greenlet class used to spawn the greenlet
"""
try:
from greenlet import getcurrent
except ImportError as exc:
raise YappiError(f"'greenlet' import failed with: {repr(exc)}")
def _get_greenlet_id():
curr_greenlet = getcurrent()
id_ = getattr(curr_greenlet, "_yappi_tid", None)
if id_ is None:
id_ = GREENLET_COUNTER()
curr_greenlet._yappi_tid = id_
return id_
def _get_greenlet_name():
return getcurrent().__class__.__name__
return _get_greenlet_id, _get_greenlet_name
def _fft(x, COL_SIZE=8):
"""
function to prettify time columns in stats.
"""
_rprecision = 6
while (_rprecision > 0):
_fmt = "%0." + "%d" % (_rprecision) + "f"
s = _fmt % (x)
if len(s) <= COL_SIZE:
break
_rprecision -= 1
return s
def _func_fullname(builtin, module, lineno, name):
if builtin:
return f"{module}.{name}"
else:
return "%s:%d %s" % (module, lineno, name)
def module_matches(stat, modules):
if not isinstance(stat, YStat):
raise YappiError(
f"Argument 'stat' shall be a YStat object. ({stat})"
)
if not isinstance(modules, list):
raise YappiError(
f"Argument 'modules' is not a list object. ({modules})"
)
if not len(modules):
raise YappiError("Argument 'modules' cannot be empty.")
if stat.full_name not in _fn_descriptor_dict:
return False
modules = set(modules)
for module in modules:
if not isinstance(module, types.ModuleType):
raise YappiError(f"Non-module item in 'modules'. ({module})")
return inspect.getmodule(_fn_descriptor_dict[stat.full_name]) in modules
def func_matches(stat, funcs):
'''
This function will not work with stats that are saved and loaded. That is
because current API of loading stats is as following:
yappi.get_func_stats(filter_callback=_filter).add('dummy.ys').print_all()
funcs: is an iterable that selects functions via method descriptor/bound method
or function object. selector type depends on the function object: If function
is a builtin method, you can use method_descriptor. If it is a builtin function
you can select it like e.g: `time.sleep`. For other cases you could use anything
that has a code object.
'''
if not isinstance(stat, YStat):
raise YappiError(
f"Argument 'stat' shall be a YStat object. ({stat})"
)
if not isinstance(funcs, list):
raise YappiError(
f"Argument 'funcs' is not a list object. ({funcs})"
)
if not len(funcs):
raise YappiError("Argument 'funcs' cannot be empty.")
if stat.full_name not in _fn_descriptor_dict:
return False
funcs = set(funcs)
for func in funcs.copy():
if not callable(func):
raise YappiError(f"Non-callable item in 'funcs'. ({func})")
# If there is no CodeObject found, use func itself. It might be a
# method descriptor, builtin func..etc.
if getattr(func, "__code__", None):
funcs.add(func.__code__)
try:
return _fn_descriptor_dict[stat.full_name] in funcs
except TypeError:
# some builtion methods like <method 'get' of 'dict' objects> are not hashable
# thus we cannot search for them in funcs set.
return False
"""
Converts our internal yappi's YFuncStats (YSTAT type) to PSTAT. So there are
some differences between the statistics parameters. The PSTAT format is as following:
PSTAT expects a dict. entry as following:
stats[("mod_name", line_no, "func_name")] = \
( total_call_count, actual_call_count, total_time, cumulative_time,
{
("mod_name", line_no, "func_name") :
(total_call_count, --> total count caller called the callee
actual_call_count, --> total count caller called the callee - (recursive calls)
total_time, --> total time caller spent _only_ for this function (not further subcalls)
cumulative_time) --> total time caller spent for this function
} --> callers dict
)
Note that in PSTAT the total time spent in the function is called as cumulative_time and
the time spent _only_ in the function as total_time. From Yappi's perspective, this means:
total_time (inline time) = tsub
cumulative_time (total time) = ttot
Other than that we hold called functions in a profile entry as named 'children'. On the
other hand, PSTAT expects to have a dict of callers of the function. So we also need to
convert children to callers dict.
From Python Docs:
'''
With cProfile, each caller is preceded by three numbers:
the number of times this specific call was made, and the total
and cumulative times spent in the current function while it was
invoked by this specific caller.
'''
That means we only need to assign ChildFuncStat's ttot/tsub values to the caller
properly. Docs indicate that when b() is called by a() pstat holds the total time
of b() when called by a, just like yappi.
PSTAT only expects to have the above dict to be saved.
"""
def convert2pstats(stats):
from collections import defaultdict
"""
Converts the internal stat type of yappi(which is returned by a call to YFuncStats.get())
as pstats object.
"""
if not isinstance(stats, YFuncStats):
raise YappiError("Source stats must be derived from YFuncStats.")
import pstats
class _PStatHolder:
def __init__(self, d):
self.stats = d
def create_stats(self):
pass
def pstat_id(fs):
return (fs.module, fs.lineno, fs.name)
_pdict = {}
# convert callees to callers
_callers = defaultdict(dict)
for fs in stats:
for ct in fs.children:
_callers[ct][pstat_id(fs)
] = (ct.ncall, ct.nactualcall, ct.tsub, ct.ttot)
# populate the pstat dict.
for fs in stats:
_pdict[pstat_id(fs)] = (
fs.ncall,
fs.nactualcall,
fs.tsub,
fs.ttot,
_callers[fs],
)
return pstats.Stats(_PStatHolder(_pdict))
def profile(clock_type="cpu", profile_builtins=False, return_callback=None):
"""
A profile decorator that can be used to profile a single call.
We need to clear_stats() on entry/exit of the function unfortunately.
As yappi is a per-interpreter resource, we cannot simply resume profiling
session upon exit of the function, that is because we _may_ simply change
start() params which may differ from the paused session that may cause instable
results. So, if you use a decorator, then global profiling may return bogus
results or no results at all.
"""
def _profile_dec(func):
def wrapper(*args, **kwargs):
if func._rec_level == 0:
clear_stats()
set_clock_type(clock_type)
start(profile_builtins, profile_threads=False)
func._rec_level += 1
try:
return func(*args, **kwargs)
finally:
func._rec_level -= 1
# only show profile information when recursion level of the
# function becomes 0. Otherwise, we are in the middle of a
# recursive call tree and not finished yet.
if func._rec_level == 0:
try:
stop()
if return_callback is None:
sys.stdout.write(LINESEP)
sys.stdout.write(
"Executed in {} {} clock seconds".format(
_fft(get_thread_stats()[0].ttot
), clock_type.upper()
)
)
sys.stdout.write(LINESEP)
get_func_stats().print_all()
else:
return_callback(func, get_func_stats())
finally:
clear_stats()
func._rec_level = 0
return wrapper
return _profile_dec
class StatString:
"""
Class to prettify/trim a profile result column.
"""
_TRAIL_DOT = ".."
_LEFT = 1
_RIGHT = 2
def __init__(self, s):
self._s = str(s)
def _trim(self, length, direction):
if (len(self._s) > length):
if direction == self._LEFT:
self._s = self._s[-length:]
return self._TRAIL_DOT + self._s[len(self._TRAIL_DOT):]
elif direction == self._RIGHT:
self._s = self._s[:length]
return self._s[:-len(self._TRAIL_DOT)] + self._TRAIL_DOT
return self._s + (" " * (length - len(self._s)))
def ltrim(self, length):
return self._trim(length, self._LEFT)
def rtrim(self, length):
return self._trim(length, self._RIGHT)
class YStat(dict):
"""
Class to hold a profile result line in a dict object, which all items can also be accessed as
instance attributes where their attribute name is the given key. Mimicked NamedTuples.
"""
_KEYS = {}
def __init__(self, values):
super().__init__()
for key, i in self._KEYS.items():
setattr(self, key, values[i])
def __setattr__(self, name, value):
self[self._KEYS[name]] = value
super().__setattr__(name, value)
class YFuncStat(YStat):
"""
Class holding information for function stats.
"""
_KEYS = {
'name': 0,
'module': 1,
'lineno': 2,
'ncall': 3,
'nactualcall': 4,
'builtin': 5,
'ttot': 6,
'tsub': 7,
'index': 8,
'children': 9,
'ctx_id': 10,
'ctx_name': 11,
'tag': 12,
'tavg': 14,
'full_name': 15
}
def __eq__(self, other):
if other is None:
return False
return self.full_name == other.full_name
def __ne__(self, other):
return not self == other
def __add__(self, other):
# do not merge if merging the same instance
if self is other:
return self
self.ncall += other.ncall
self.nactualcall += other.nactualcall
self.ttot += other.ttot
self.tsub += other.tsub
self.tavg = self.ttot / self.ncall
for other_child_stat in other.children:
# all children point to a valid entry, and we shall have merged previous entries by here.
self.children.append(other_child_stat)
return self
def __hash__(self):
return hash(self.full_name)
def is_recursive(self):
# we have a known bug where call_leave not called for some thread functions(run() especially)
# in that case ncalls will be updated in call_enter, however nactualcall will not. This is for
# checking that case.
if self.nactualcall == 0:
return False
return self.ncall != self.nactualcall
def strip_dirs(self):
self.module = os.path.basename(self.module)
self.full_name = _func_fullname(
self.builtin, self.module, self.lineno, self.name
)
return self
def _print(self, out, columns):
for x in sorted(columns.keys()):
title, size = columns[x]
if title == "name":
out.write(StatString(self.full_name).ltrim(size))
out.write(" " * COLUMN_GAP)
elif title == "ncall":
if self.is_recursive():
out.write(
StatString("%d/%d" % (self.ncall, self.nactualcall)
).rtrim(size)
)
else:
out.write(StatString(self.ncall).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "tsub":
out.write(StatString(_fft(self.tsub, size)).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "ttot":
out.write(StatString(_fft(self.ttot, size)).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "tavg":
out.write(StatString(_fft(self.tavg, size)).rtrim(size))
out.write(LINESEP)
class YChildFuncStat(YFuncStat):
"""
Class holding information for children function stats.
"""
_KEYS = {
'index': 0,
'ncall': 1,
'nactualcall': 2,
'ttot': 3,
'tsub': 4,
'tavg': 5,
'builtin': 6,
'full_name': 7,
'module': 8,
'lineno': 9,
'name': 10
}
def __add__(self, other):
if other is None:
return self
self.nactualcall += other.nactualcall
self.ncall += other.ncall
self.ttot += other.ttot
self.tsub += other.tsub
self.tavg = self.ttot / self.ncall
return self
class YThreadStat(YStat):
"""
Class holding information for thread stats.
"""
_KEYS = {
'name': 0,
'id': 1,
'tid': 2,
'ttot': 3,
'sched_count': 4,
}
def __eq__(self, other):
if other is None:
return False
return self.id == other.id
def __ne__(self, other):
return not self == other
def __hash__(self, *args, **kwargs):
return hash(self.id)
def _print(self, out, columns):
for x in sorted(columns.keys()):
title, size = columns[x]
if title == "name":
out.write(StatString(self.name).ltrim(size))
out.write(" " * COLUMN_GAP)
elif title == "id":
out.write(StatString(self.id).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "tid":
out.write(StatString(self.tid).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "ttot":
out.write(StatString(_fft(self.ttot, size)).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "scnt":
out.write(StatString(self.sched_count).rtrim(size))
out.write(LINESEP)
class YGreenletStat(YStat):
"""
Class holding information for thread stats.
"""
_KEYS = {
'name': 0,
'id': 1,
'ttot': 3,
'sched_count': 4,
}
def __eq__(self, other):
if other is None:
return False
return self.id == other.id
def __ne__(self, other):
return not self == other
def __hash__(self, *args, **kwargs):
return hash(self.id)
def _print(self, out, columns):
for x in sorted(columns.keys()):
title, size = columns[x]
if title == "name":
out.write(StatString(self.name).ltrim(size))
out.write(" " * COLUMN_GAP)
elif title == "id":
out.write(StatString(self.id).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "ttot":
out.write(StatString(_fft(self.ttot, size)).rtrim(size))
out.write(" " * COLUMN_GAP)
elif title == "scnt":
out.write(StatString(self.sched_count).rtrim(size))
out.write(LINESEP)
class YStats:
"""
Main Stats class where we collect the information from _yappi and apply the user filters.
"""
def __init__(self):
self._clock_type = None
self._as_dict = {}
self._as_list = []
def get(self):
self._clock_type = _yappi.get_clock_type()
self.sort(DEFAULT_SORT_TYPE, DEFAULT_SORT_ORDER)
return self
def sort(self, sort_type, sort_order):
# sort case insensitive for strings
self._as_list.sort(
key=lambda stat: stat[sort_type].lower() \
if isinstance(stat[sort_type], str) else stat[sort_type],
reverse=(sort_order == SORT_ORDERS["desc"])
)
return self
def clear(self):
del self._as_list[:]
self._as_dict.clear()
def empty(self):
return (len(self._as_list) == 0)
def __getitem__(self, key):
try:
return self._as_list[key]
except IndexError:
return None
def count(self, item):
return self._as_list.count(item)
def __iter__(self):
return iter(self._as_list)
def __len__(self):
return len(self._as_list)
def pop(self):
item = self._as_list.pop()
del self._as_dict[item]
return item
def append(self, item):
# increment/update the stat if we already have it
existing = self._as_dict.get(item)
if existing:
existing += item
return
self._as_list.append(item)
self._as_dict[item] = item
def _print_header(self, out, columns):
for x in sorted(columns.keys()):
title, size = columns[x]
if len(title) > size:
raise YappiError("Column title exceeds available length[%s:%d]" % \
(title, size))
out.write(title)
out.write(" " * (COLUMN_GAP + size - len(title)))
out.write(LINESEP)
def _debug_check_sanity(self):
"""
Check for basic sanity errors in stats. e.g: Check for duplicate stats.
"""
for x in self:
if self.count(x) > 1:
return False
return True
class YStatsIndexable(YStats):
def __init__(self):
super().__init__()
self._additional_indexing = {}
def clear(self):
super().clear()
self._additional_indexing.clear()
def pop(self):
item = super().pop()
self._additional_indexing.pop(item.index, None)
self._additional_indexing.pop(item.full_name, None)
return item
def append(self, item):
super().append(item)
# setdefault so that we don't replace them if they're already there.
self._additional_indexing.setdefault(item.index, item)
self._additional_indexing.setdefault(item.full_name, item)
def __getitem__(self, key):
if isinstance(key, int):
# search by item.index
return self._additional_indexing.get(key, None)
elif isinstance(key, str):
# search by item.full_name
return self._additional_indexing.get(key, None)
elif isinstance(key, YFuncStat) or isinstance(key, YChildFuncStat):
return self._additional_indexing.get(key.index, None)
return super().__getitem__(key)
class YChildFuncStats(YStatsIndexable):
def sort(self, sort_type, sort_order="desc"):
sort_type = _validate_sorttype(sort_type, SORT_TYPES_CHILDFUNCSTATS)
sort_order = _validate_sortorder(sort_order)
return super().sort(
SORT_TYPES_CHILDFUNCSTATS[sort_type], SORT_ORDERS[sort_order]
)
def print_all(
self,
out=sys.stdout,
columns={
0: ("name", 36),
1: ("ncall", 5),
2: ("tsub", 8),
3: ("ttot", 8),
4: ("tavg", 8)
}
):
"""
Prints all of the child function profiler results to a given file. (stdout by default)
"""
if self.empty() or len(columns) == 0:
return
for _, col in columns.items():
_validate_columns(col[0], COLUMNS_FUNCSTATS)
out.write(LINESEP)
self._print_header(out, columns)
for stat in self:
stat._print(out, columns)
def strip_dirs(self):
for stat in self:
stat.strip_dirs()
return self
class YFuncStats(YStatsIndexable):
_idx_max = 0
_sort_type = None
_sort_order = None
_SUPPORTED_LOAD_FORMATS = ['YSTAT']
_SUPPORTED_SAVE_FORMATS = ['YSTAT', 'CALLGRIND', 'PSTAT']
def __init__(self, files=[]):
super().__init__()
self.add(files)
self._filter_callback = None
def strip_dirs(self):
for stat in self:
stat.strip_dirs()
stat.children.strip_dirs()
return self
def get(self, filter={}, filter_callback=None):
_yappi._pause()
self.clear()
try:
self._filter_callback = filter_callback
_yappi.enum_func_stats(self._enumerator, filter)
self._filter_callback = None
# convert the children info from tuple to YChildFuncStat
for stat in self:
_childs = YChildFuncStats()
for child_tpl in stat.children:
rstat = self[child_tpl[0]]
# sometimes even the profile results does not contain the result because of filtering
# or timing(call_leave called but call_enter is not), with this we ensure that the children
# index always point to a valid stat.
if rstat is None:
continue
tavg = rstat.ttot / rstat.ncall
cfstat = YChildFuncStat(
child_tpl + (
tavg,
rstat.builtin,
rstat.full_name,
rstat.module,
rstat.lineno,
rstat.name,
)
)
_childs.append(cfstat)
stat.children = _childs
result = super().get()
finally:
_yappi._resume()
return result
def _enumerator(self, stat_entry):
global _fn_descriptor_dict
fname, fmodule, flineno, fncall, fnactualcall, fbuiltin, fttot, ftsub, \
findex, fchildren, fctxid, fctxname, ftag, ffn_descriptor = stat_entry
# builtin function?
ffull_name = _func_fullname(bool(fbuiltin), fmodule, flineno, fname)
ftavg = fttot / fncall
fstat = YFuncStat(stat_entry + (ftavg, ffull_name))
_fn_descriptor_dict[ffull_name] = ffn_descriptor
# do not show profile stats of yappi itself.
if os.path.basename(
fstat.module
) == "yappi.py" or fstat.module == "_yappi":
return
fstat.builtin = bool(fstat.builtin)
if self._filter_callback:
if not self._filter_callback(fstat):
return
self.append(fstat)
# hold the max idx number for merging new entries(for making the merging
# entries indexes unique)
if self._idx_max < fstat.index:
self._idx_max = fstat.index
def _add_from_YSTAT(self, file):
try:
saved_stats, saved_clock_type = pickle.load(file)
except:
raise YappiError(
f"Unable to load the saved profile information from {file.name}."
)
# check if we really have some stats to be merged?
if not self.empty():
if self._clock_type != saved_clock_type and self._clock_type is not None:
raise YappiError("Clock type mismatch between current and saved profiler sessions.[%s,%s]" % \
(self._clock_type, saved_clock_type))
self._clock_type = saved_clock_type
# add 'not present' previous entries with unique indexes
for saved_stat in saved_stats:
if saved_stat not in self:
self._idx_max += 1
saved_stat.index = self._idx_max
self.append(saved_stat)
# fix children's index values
for saved_stat in saved_stats:
for saved_child_stat in saved_stat.children:
# we know for sure child's index is pointing to a valid stat in saved_stats
# so as saved_stat is already in sync. (in above loop), we can safely assume
# that we shall point to a valid stat in current_stats with the child's full_name
saved_child_stat.index = self[saved_child_stat.full_name].index
# merge stats
for saved_stat in saved_stats:
saved_stat_in_curr = self[saved_stat.full_name]
saved_stat_in_curr += saved_stat
def _save_as_YSTAT(self, path):
with open(path, "wb") as f:
pickle.dump((self, self._clock_type), f, YPICKLE_PROTOCOL)
def _save_as_PSTAT(self, path):
"""
Save the profiling information as PSTAT.
"""
_stats = convert2pstats(self)
_stats.dump_stats(path)
def _save_as_CALLGRIND(self, path):
"""
Writes all the function stats in a callgrind-style format to the given
file. (stdout by default)
"""
header = """version: 1\ncreator: %s\npid: %d\ncmd: %s\npart: 1\n\nevents: Ticks""" % \
('yappi', os.getpid(), ' '.join(sys.argv))
lines = [header]
# add function definitions
file_ids = ['']
func_ids = ['']
func_idx_list = []
for func_stat in self:
file_ids += ['fl=(%d) %s' % (func_stat.index, func_stat.module)]
func_ids += [
'fn=(%d) %s %s:%s' % (
func_stat.index, func_stat.name, func_stat.module,
func_stat.lineno
)
]
func_idx_list.append(func_stat.index)
# also adds function information for children
for child in func_stat.children:
# ... but make sure to add each function only once
if child.index in func_idx_list:
continue
file_ids += ['fl=(%d) %s' % (child.index, child.module)]
func_ids += [
'fn=(%d) %s %s:%s' % (
child.index, child.name, child.module,
child.lineno
)
]
func_idx_list.append(child.index)
lines += file_ids + func_ids
# add stats for each function we have a record of
for func_stat in self:
func_stats = [
'',
'fl=(%d)' % func_stat.index,
'fn=(%d)' % func_stat.index
]
func_stats += [
f'{func_stat.lineno} {int(func_stat.tsub * 1e6)}'
]
# children functions stats
for child in func_stat.children:
func_stats += [
'cfl=(%d)' % child.index,
'cfn=(%d)' % child.index,
'calls=%d 0' % child.ncall,
'0 %d' % int(child.ttot * 1e6)
]
lines += func_stats
with open(path, "w") as f:
f.write('\n'.join(lines))
def add(self, files, type="ystat"):
type = type.upper()
if type not in self._SUPPORTED_LOAD_FORMATS:
raise NotImplementedError(
'Loading from (%s) format is not possible currently.'
)
if isinstance(files, str):
files = [
files,
]
for fd in files:
with open(fd, "rb") as f:
add_func = getattr(self, f"_add_from_{type}")
add_func(file=f)