← Back to DAGDA | Support | Source: https://github.com/python/cpython/pull/5103/commits/9283cb7aefc9ab6750649a53c96c36f5a9bc3da1
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
Prev Previous commit
Next Next commit
Incorporate review comments
  • Loading branch information
mwidjaja committed Jan 26, 2018
commit 9283cb7aefc9ab6750649a53c96c36f5a9bc3da1
63 changes: 33 additions & 30 deletions Doc/library/profile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ The :mod:`pstats` module's :class:`~pstats.Stats` class has a variety of methods
for manipulating and printing the data saved into a profile results file::

import pstats
from pstats import SortKey
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()

Expand All @@ -148,14 +149,14 @@ entries according to the standard module/line/name string that is printed. The
:meth:`~pstats.Stats.print_stats` method printed out all the statistics. You
might try the following sort calls::

p.sort_stats(SortKey.name)
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::

p.sort_stats(SortKey.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 @@ -164,20 +165,20 @@ taking time, the above line is what you would use.
If you were looking to see what functions were looping a lot, and taking a lot
of time, you would do::

p.sort_stats(SortKey.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(SortKey.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(SortKey.time, SortKey.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 @@ -250,12 +251,13 @@ functions:
without writing the profile data to a file::

import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = SortKey.cumulative
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
Expand Down Expand Up @@ -362,63 +364,64 @@ Analysis of the profiler data is done using the :class:`~pstats.Stats` class.

This method modifies the :class:`Stats` object by sorting it according to
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
enum 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(SortKey.name, SortKey.file)`` will sort
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:
long as the abbreviation is unambiguous.

The following are the valid string and SortKey:

+------------------+---------------------+----------------------+
| Valid String Arg | Valid enum Arg | Meaning |
+==================+=====================+======================+
| ``'calls'`` | SortKey.calls | call count |
| ``'calls'`` | SortKey.CALLS | call count |
+------------------+---------------------+----------------------+
| ``'cumulative'`` | SortKey.cumulative | cumulative time |
| ``'cumulative'`` | SortKey.CUMULATIVE | cumulative time |
+------------------+---------------------+----------------------+
| ``'cumtime'`` | SortKey.cumtime | cumulative time |
| ``'cumtime'`` | N/A | cumulative time |
+------------------+---------------------+----------------------+
| ``'file'`` | SortKey.file | file name |
| ``'file'`` | N/A | file name |
+------------------+---------------------+----------------------+
| ``'filename'`` | SortKey.filename | file name |
| ``'filename'`` | N/A | file name |
+------------------+---------------------+----------------------+
| ``'module'`` | SortKey.module | file name |
| ``'module'`` | SortKey.MODULE | file name |
+------------------+---------------------+----------------------+
| ``'ncalls'`` | SortKey.ncalls | call count |
| ``'ncalls'`` | N/A | call count |
+------------------+---------------------+----------------------+
| ``'pcalls'`` | SortKey.pcalls | primitive call count |
| ``'pcalls'`` | SortKey.PCALLS | primitive call count |
+------------------+---------------------+----------------------+
| ``'line'`` | SortKey.line | line number |
| ``'line'`` | SortKey.LINE | line number |
+------------------+---------------------+----------------------+
| ``'name'`` | SortKey.name | function name |
| ``'name'`` | SortKey.NAME | function name |
+------------------+---------------------+----------------------+
| ``'nfl'`` | SortKey.nfl | name/file/line |
| ``'nfl'`` | SortKey.NFL | name/file/line |
+------------------+---------------------+----------------------+
| ``'stdname'`` | SortKey.stdname | standard name |
| ``'stdname'`` | SortKey.STDNAME | standard name |
+------------------+---------------------+----------------------+
| ``'time'`` | SortKey.time | internal time |
| ``'time'`` | SortKey.TIME | internal time |
+------------------+---------------------+----------------------+
| ``'tottime'`` | SortKey.tottime | internal time |
| ``'tottime'`` | N/A | 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
``SortKey.nfl`` and ``SortKey.stdname`` is that the standard name is a
``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)``.
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 @@ -429,7 +432,7 @@ 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.
Added the SortKey enum.

.. method:: reverse_order()

Expand Down
60 changes: 30 additions & 30 deletions Lib/pstats.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,24 @@


class SortKey(str, Enum):
CALLS = 'calls'
NCALLS = 'ncalls'
CUMULATIVE = 'cumulative'
CUMTIME = 'cumulative'
MODULE = 'module'
FILE = 'file'
FILENAME = 'filename'
CALLS = 'calls', 'ncalls'
CUMULATIVE = 'cumulative', 'cumtime'
MODULE = 'module', 'filename', 'file'
LINE = 'line'
NAME = 'name'
NFL = 'nfl'
PCALLS = 'pcalls'
STDNAME = 'stdname'
TIME = 'time'
TOTTIME = 'tottime'
TIME = 'time', 'tottime'

def __new__(cls, *values):
obj = str.__new__(cls)

obj._value_ = values[0]
for other_value in values[1:]:
cls._value2member_map_[other_value] = obj
obj._all_values = values
return obj

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:
Expand Down Expand Up @@ -177,20 +181,20 @@ def dump_stats(self, filename):
# list the tuple indices and directions for sorting,
# along with some printable description
sort_arg_dict_default = {
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"),
"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"),
}

def get_sort_arg_defs(self):
Expand Down Expand Up @@ -227,18 +231,14 @@ def sort_stats(self, *field):
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:
for word in field:
if isinstance(word, str) and word == 'cumtime':
word = 'cumulative'
sort_arg_defs = self.get_sort_arg_defs()
sort_arg_defs = self.get_sort_arg_defs()

sort_tuple = ()
self.sort_type = ""
connector = ""
for word in field:
if isinstance(word, SortKey):
word = word.value
sort_tuple = sort_tuple + sort_arg_defs[word][0]
self.sort_type += connector + sort_arg_defs[word][1]
connector = ", "
Expand Down
20 changes: 11 additions & 9 deletions Lib/test/test_pstats.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,23 @@ def test_sort_stats_int(self):
self.stats.sort_arg_dict_default[arg_str][-1])

def test_sort_stats_string(self):
for arg in SortKey:
arg = arg.value
for sort_name in ('calls', 'ncalls', 'cumtime', 'cumulative', 'file',
'filename', 'line', 'module', 'name', 'nfl', 'pcalls',
'stdname', 'time', 'tottime'):
# 'file' sorting criteria will not work because it creates
# ambiquity with 'filename'
if arg == 'file':
if sort_name == 'file':
continue
self.stats.sort_stats(arg)
self.stats.sort_stats(sort_name)
self.assertEqual(self.stats.sort_type,
self.stats.sort_arg_dict_default[arg][-1])
self.stats.sort_arg_dict_default[sort_name][-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])
for member in SortKey:
self.stats.sort_stats(member)
self.assertEqual(
self.stats.sort_type,
self.stats.sort_arg_dict_default[member.value][-1])

def test_sort_starts_mix(self):
self.assertRaises(TypeError, self.stats.sort_stats,
Expand Down