如何利用sys.callstats?

How to utilize sys.callstats?

我刚刚在 PyCharm 之后的 sys 模块中偶然发现了 callstats 自动完成建议它。否则我可能永远不会发现它 因为它甚至没有在 docs

中被提及

help(sys.callstats) 给出这个:

 Help on built-in function callstats in module sys:
callstats(...)
    callstats() -> tuple of integers

    Return a tuple of function call statistics, if CALL_PROFILE was defined
    when Python was built.  Otherwise, return None.

    When enabled, this function returns detailed, implementation-specific
    details about the number of function calls executed. The return value is
    a 11-tuple where the entries in the tuple are counts of:
    0. all function calls
    1. calls to PyFunction_Type objects
    2. PyFunction calls that do not create an argument tuple
    3. PyFunction calls that do not create an argument tuple
       and bypass PyEval_EvalCodeEx()
    4. PyMethod calls
    5. PyMethod calls on bound methods
    6. PyType calls
    7. PyCFunction calls
    8. generator calls
    9. All other calls
    10. Number of stack pops performed by call_function() 

现在我很好奇为什么它没有在任何地方被提及,以及是否有可能在 Python 的 Anaconda 构建中使用它。 它 returns None 当我打电话给 sys.callstats() 所以我假设后者的答案是否定的。 但是,我仍然有兴趣了解 Python 构建的实际输出结果 这在哪里有效。


编辑: 在接受答案下方的评论链接的 Issue28799 中,我们找到了 callstats 将被 Python 3.7 删除的原因。在实施即将推出的功能后,统计数据可能不会正确:

My problem is that with my work on FASTCALL, it became harder to track where the functions are called in practice. It maybe out of the Python/ceval.c file. I'm not sure that statistics are still computed correctly after my FASTCALL changes, and I don't know how to check it.

Python has already sys.setprofile(), cProfile and profile modules. There is also sys.settrace(). Do we still need CALL_PROFILE?

Attached patch removes the feature:

  • Calling the the untested and undocumented sys.callstats() function now emits a DeprecationWarning warning
  • Remove the PyEval_GetCallStats() function and its documentation

我对sys.callstats也很好奇,所以我用CALL_PROFILE标志编译了一个Python 2.7.12的二进制文件。使用零用户代码但只有 python bootstrap 个例程,sys.callstats() 的结果是:

PCALL_ALL 1691
PCALL_FUNCTION 371
PCALL_FAST_FUNCTION 363
PCALL_FASTER_FUNCTION 257
PCALL_METHOD 59
PCALL_BOUND_METHOD 58
PCALL_CFUNCTION 892
PCALL_TYPE 394
PCALL_GENERATOR 28
PCALL_OTHER 33
PCALL_POP 2005

不要。它未记录、未测试,并且 disabled in Python 3.7. If you want to do profiling, use cProfile, profile, or sys.setprofile.

目前,如果您从定义了 CALL_PROFILE 的源代码编译 Python 3.6 或 2.7,那么 sys.callstats 将完全按照文档字符串所说的那样使用 CALL_PROFILE 定义: 它 returns 一个包含各种内部调用类型计数的 11 元素元组。仅在 Python/ceval.c 中跟踪统计数据,因此它会错过未通过那里的呼叫。