← Back to DAGDA | Support | Source: https://github.com/python/cpython/pull/5103/commits/c28feaa506d86e902e8625bcc8c62262ed859b3c
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
bpo-29237: Create enum for pstats sorting options
  • Loading branch information
mwidjaja committed Jan 26, 2018
commit c28feaa506d86e902e8625bcc8c62262ed859b3c
115 changes: 65 additions & 50 deletions Doc/library/profile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,17 @@ might try the following sort calls::
p.sort_stats('name')
p.print_stats()

p.sort_stats(SortKey.name)
p.print_stats()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello and thanks for the PR!

Here I would recomment keeping only the example with the enum, since it’s the way that we want to recommend.

To match the import style (see import pstats in the previous code block), the example would need to be p.sort_stats(pstats.SortKey.NAME) (assuming the upper-case fix asked by the other reviewer is done).

I wonder if the enum should be defined on the Stats class, to make code shorter: p.sort_stats(p.SortKey.NAME). Maybe worth asking on the ticket to get other people’s opinion.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would change the import to

from pstats import Stats, SortKey

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pstats module is all about stats processing, so there is no need to hide SortKey inside the Stats class.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the comment. Re: 'Here I would recomment keeping only the example with the enum, since it’s the way that we want to recommend.' I could do that, but I have also received comment about having both example as the string argument is still valid. Showing only the enum would make the doc incomplete.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes there is a need to also show an example with a string form, but not all code examples need both forms.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mwidjaja

When you make the duplicate SortKeys actually duplicates, please put the better name first -- something like:

class SortKey(str, Enum):
    calls = 'calls'
    ncalls = 'calls'
    cumulative = 'cumulative'
    cumtime = 'cumulative'
    module = 'module'
    file = 'module'
    filename = 'module'
    line = 'line'
    name = 'name'
    nfl = 'nfl'
    pcalls = 'pcalls'
    stdname = 'stdname'
    time = 'time'
    tottime = 'time'


The first call will actually sort the list by function name, and the second call
will print out the statistics. The following are some interesting calls to
experiment with::
will print out the statistics. The next two calls perform the same function, but
the call to :meth:`~pstats.Stats.sort_stats` uses SortKey enum argument which is
less error prone than the string version. The following are some interesting calls
to experiment with::

p.sort_stats('cumulative').print_stats(10)
p.sort_stats(SortKey.cumulative).print_stats(10)

This sorts the profile by cumulative time in a function, and then only prints
the ten most significant lines. If you want to understand what algorithms are
Expand All @@ -165,19 +171,22 @@ If you were looking to see what functions were looping a lot, and taking a lot
of time, you would do::

p.sort_stats('time').print_stats(10)
p.sort_stats(SortKey.time).print_stats(10)

to sort according to time spent within each function, and then print the
statistics for the top ten functions.

You might also try::

p.sort_stats('file').print_stats('__init__')
p.sort_stats(SortKey.file).print_stats('__init__')

This will sort all the statistics by file name, and then print out statistics
for only the class init methods (since they are spelled with ``__init__`` in
them). As one final example, you could try::

p.sort_stats('time', 'cumulative').print_stats(.5, 'init')
p.sort_stats(SortKey.time, SortKey.cumulative).print_stats(.5, 'init')

This line sorts statistics with a primary key of time, and a secondary key of
cumulative time, and then prints out some of the statistics. To be specific, the
Expand Down Expand Up @@ -255,7 +264,7 @@ functions:
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
sortby = SortKey.cumulative
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
Expand Down Expand Up @@ -361,60 +370,64 @@ Analysis of the profiler data is done using the :class:`~pstats.Stats` class.
.. method:: sort_stats(*keys)

This method modifies the :class:`Stats` object by sorting it according to
the supplied criteria. The argument is typically a string identifying the
basis of a sort (example: ``'time'`` or ``'name'``).
the supplied criteria. The argument can be either a string or a SortKey
enums identifying the basis of a sort (example: ``'time'``, ``'name'``,
``SortKey.time`` or ``SortKey.name``). The SortKey enums argument have
advantage over the string argument in that it is more robust and less
error prone.

When more than one key is provided, then additional keys are used as
secondary criteria when there is equality in all keys selected before
them. For example, ``sort_stats('name', 'file')`` will sort all the
entries according to their function name, and resolve all ties (identical
function names) by sorting by file name.

Abbreviations can be used for any key names, as long as the abbreviation
is unambiguous. The following are the keys currently defined:

+------------------+----------------------+
| Valid Arg | Meaning |
+==================+======================+
| ``'calls'`` | call count |
+------------------+----------------------+
| ``'cumulative'`` | cumulative time |
+------------------+----------------------+
| ``'cumtime'`` | cumulative time |
+------------------+----------------------+
| ``'file'`` | file name |
+------------------+----------------------+
| ``'filename'`` | file name |
+------------------+----------------------+
| ``'module'`` | file name |
+------------------+----------------------+
| ``'ncalls'`` | call count |
+------------------+----------------------+
| ``'pcalls'`` | primitive call count |
+------------------+----------------------+
| ``'line'`` | line number |
+------------------+----------------------+
| ``'name'`` | function name |
+------------------+----------------------+
| ``'nfl'`` | name/file/line |
+------------------+----------------------+
| ``'stdname'`` | standard name |
+------------------+----------------------+
| ``'time'`` | internal time |
+------------------+----------------------+
| ``'tottime'`` | internal time |
+------------------+----------------------+
them. For example, ``sort_stats(SortKey.name, SortKey.file)`` will sort
all the entries according to their function name, and resolve all ties
(identical function names) by sorting by file name.

For the string argument, abbreviations can be used for any key names, as
long as the abbreviation is unambiguous. The following are the keys
currently defined:

+------------------+---------------------+----------------------+
| Valid String Arg | Valid enum Arg | Meaning |
+==================+=====================+======================+
| ``'calls'`` | SortKey.calls | call count |
+------------------+---------------------+----------------------+
| ``'cumulative'`` | SortKey.cumulative | cumulative time |
+------------------+---------------------+----------------------+
| ``'cumtime'`` | SortKey.cumtime | cumulative time |
+------------------+---------------------+----------------------+
| ``'file'`` | SortKey.file | file name |
+------------------+---------------------+----------------------+
| ``'filename'`` | SortKey.filename | file name |
+------------------+---------------------+----------------------+
| ``'module'`` | SortKey.module | file name |
+------------------+---------------------+----------------------+
| ``'ncalls'`` | SortKey.ncalls | call count |
+------------------+---------------------+----------------------+
| ``'pcalls'`` | SortKey.pcalls | primitive call count |
+------------------+---------------------+----------------------+
| ``'line'`` | SortKey.line | line number |
+------------------+---------------------+----------------------+
| ``'name'`` | SortKey.name | function name |
+------------------+---------------------+----------------------+
| ``'nfl'`` | SortKey.nfl | name/file/line |
+------------------+---------------------+----------------------+
| ``'stdname'`` | SortKey.stdname | standard name |
+------------------+---------------------+----------------------+
| ``'time'`` | SortKey.time | internal time |
+------------------+---------------------+----------------------+
| ``'tottime'`` | SortKey.tottime | internal time |
+------------------+---------------------+----------------------+

Note that all sorts on statistics are in descending order (placing most
time consuming items first), where as name, file, and line number searches
are in ascending order (alphabetical). The subtle distinction between
``'nfl'`` and ``'stdname'`` is that the standard name is a sort of the
name as printed, which means that the embedded line numbers get compared
in an odd way. For example, lines 3, 20, and 40 would (if the file names
were the same) appear in the string order 20, 3 and 40. In contrast,
``'nfl'`` does a numeric compare of the line numbers. In fact,
``sort_stats('nfl')`` is the same as ``sort_stats('name', 'file',
'line')``.
``SortKey.nfl`` and ``SortKey.stdname`` is that the standard name is a
sort of the name as printed, which means that the embedded line numbers
get compared in an odd way. For example, lines 3, 20, and 40 would (if
the file names were the same) appear in the string order 20, 3 and 40.
In contrast, ``SortKey.nfl`` does a numeric compare of the line numbers.
In fact, ``sort_stats(SortKey.nfl)`` is the same as
``sort_stats(SortKey.name, SortKey.file, SortKey.line)``.

For backward-compatibility reasons, the numeric arguments ``-1``, ``0``,
``1``, and ``2`` are permitted. They are interpreted as ``'stdname'``,
Expand All @@ -424,6 +437,8 @@ Analysis of the profiler data is done using the :class:`~pstats.Stats` class.

.. For compatibility with the old profiler.

.. versionadded:: 3.7
Added the SortKey enums.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enum*


.. method:: reverse_order()

Expand Down
72 changes: 50 additions & 22 deletions Lib/pstats.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,28 @@
import time
import marshal
import re
from enum import Enum
from functools import cmp_to_key

__all__ = ["Stats"]
__all__ = ["Stats", "SortKey"]


class SortKey(str, Enum):
calls = 'calls'
ncalls = 'ncalls'
cumtime = 'cumtime'
cumulative = 'cumulative'
file = 'file'
filename = 'filename'
line = 'line'
module = 'module'
name = 'name'
nfl = 'nfl'
pcalls = 'pcalls'
stdname = 'stdname'
time = 'time'
tottime = 'tottime'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My initial understanding of this was flawed. Since we need to support the old string values we can't just have CUMTIME and CUMULATIVE map to "cumulative" because then "cumtime" is gone (unless we do extra work, which I see you did).

What we need here is a MultiValueEnum, so SortKey.CUMULATIVE maps to both "cumulative" and "cumtime".

The Enum should look like this:

class SortKey(str, Enum):

    CALLS = 'calls', 'ncalls'
    CUMULATIVE = 'cumulative', "cumtime"
    MODULE = 'module', 'filename', 'file'
    LINE = 'line'
    NAME = 'name'
    NFL = 'nfl'
    PCALLS = 'pcalls'
    STDNAME = 'stdname'
    TIME = 'time', 'tottime'

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

Operations like SortKey('file') will return SortKey.MODULE. The downside is that SortKey.FILE is undefined, but I think that is an acceptable trade-off since we are still supporting the original string values, and those values can be used to get a correct SortKey member.


class Stats:
"""This class is used for creating reports from data generated by the
Expand All @@ -49,13 +68,14 @@ class Stats:

The sort_stats() method now processes some additional options (i.e., in
addition to the old -1, 0, 1, or 2 that are respectively interpreted as
'stdname', 'calls', 'time', and 'cumulative'). It takes an arbitrary number
of quoted strings to select the sort order.
'stdname', 'calls', 'time', and 'cumulative'). It takes either an
arbitrary number of quoted strings or SortKey enum to select the sort
order.

For example sort_stats('time', 'name') sorts on the major key of 'internal
function time', and on the minor key of 'the name of the function'. Look at
the two tables in sort_stats() and get_sort_arg_defs(self) for more
examples.
For example sort_stats('time', 'name') or sort_stats(SortKey.time,
SortKey.name) sorts on the major key of 'internal function time', and on
the minor key of 'the name of the function'. Look at the two tables in
sort_stats() and get_sort_arg_defs(self) for more examples.

All methods return self, so you can string together commands like:
Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
Expand Down Expand Up @@ -157,20 +177,20 @@ def dump_stats(self, filename):
# list the tuple indices and directions for sorting,
# along with some printable description
sort_arg_dict_default = {
"calls" : (((1,-1), ), "call count"),
"ncalls" : (((1,-1), ), "call count"),
"cumtime" : (((3,-1), ), "cumulative time"),
"cumulative": (((3,-1), ), "cumulative time"),
"file" : (((4, 1), ), "file name"),
"filename" : (((4, 1), ), "file name"),
"line" : (((5, 1), ), "line number"),
"module" : (((4, 1), ), "file name"),
"name" : (((6, 1), ), "function name"),
"nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
"pcalls" : (((0,-1), ), "primitive call count"),
"stdname" : (((7, 1), ), "standard name"),
"time" : (((2,-1), ), "internal time"),
"tottime" : (((2,-1), ), "internal time"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we still have to support string arguments, and the SortKey members are also strings, I would just leave the original code alone here.

SortKey.calls : (((1,-1), ), "call count"),
SortKey.ncalls : (((1,-1), ), "call count"),
SortKey.cumtime : (((3,-1), ), "cumulative time"),
SortKey.cumulative: (((3,-1), ), "cumulative time"),
SortKey.file : (((4, 1), ), "file name"),
SortKey.filename : (((4, 1), ), "file name"),
SortKey.line : (((5, 1), ), "line number"),
SortKey.module : (((4, 1), ), "file name"),
SortKey.name : (((6, 1), ), "function name"),
SortKey.nfl : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
SortKey.pcalls : (((0,-1), ), "primitive call count"),
SortKey.stdname : (((7, 1), ), "standard name"),
SortKey.time : (((2,-1), ), "internal time"),
SortKey.tottime : (((2,-1), ), "internal time"),
}

def get_sort_arg_defs(self):
Expand Down Expand Up @@ -202,8 +222,16 @@ def sort_stats(self, *field):
0: "calls",
1: "time",
2: "cumulative"}[field[0]] ]
elif len(field) >= 2:
for arg in field[1:]:
if type(arg) != type(field[0]):
raise TypeError("Can't have mixed argument type")

if isinstance(field[0], SortKey):
sort_arg_defs = self.sort_arg_dict_default
else:
sort_arg_defs = self.get_sort_arg_defs()

sort_arg_defs = self.get_sort_arg_defs()
sort_tuple = ()
self.sort_type = ""
connector = ""
Expand Down
36 changes: 36 additions & 0 deletions Lib/test/test_pstats.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from test import support
from io import StringIO
import pstats
from pstats import SortKey



Expand Down Expand Up @@ -33,6 +34,41 @@ def test_add(self):
stats = pstats.Stats(stream=stream)
stats.add(self.stats, self.stats)

def test_sort_stats_int(self):
valid_args = {-1: 'stdname',
0: 'calls',
1: 'time',
2: 'cumulative'}
for arg_int, arg_str in valid_args.items():
self.stats.sort_stats(arg_int)
self.assertEqual(self.stats.sort_type,
self.stats.sort_arg_dict_default[arg_str][-1])

def test_sort_stats_string(self):
for arg in SortKey:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is the string test, we should be iterating through all the possible strings (no longer a given with the new SortKey enum). Listing them all is probably the best way to go:

for arg in ('calls', 'ncalls', 'cumtime', 'cumulative', ... ):

arg = arg.name
# 'file' sorting criteria will not work because it creates
# ambiquity with 'filename'
if arg == 'file':
continue
self.stats.sort_stats(arg)
self.assertEqual(self.stats.sort_type,
self.stats.sort_arg_dict_default[arg][-1])

def test_sort_stats_enum(self):
for arg in SortKey:
self.stats.sort_stats(arg)
self.assertEqual(self.stats.sort_type,
self.stats.sort_arg_dict_default[arg][-1])

def test_sort_starts_mix(self):
self.assertRaises(TypeError, self.stats.sort_stats,
'calls',
SortKey.time)
self.assertRaises(TypeError, self.stats.sort_stats,
SortKey.time,
'calls')


if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1706,6 +1706,7 @@ Jeff Wheeler
Christopher White
David White
Mats Wichmann
Marcel Widjaja
Truida Wiedijk
Felix Wiemann
Gerry Wiener
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Create enum for pstats sorting options