[파이썬] `sys.callstats()`: 인터프리터 호출 통계 반환

In Python, the sys module provides a variety of functions and variables that allow you to interact with the Python interpreter. One useful function provided by the sys module is sys.callstats(), which returns the call statistics for the interpreter.

Understanding sys.callstats()

The sys.callstats() function returns a tuple containing four elements that represent the call statistics for the Python interpreter:

  1. call_stats: This element is a dictionary that provides information about the number of calls made to each function throughout the execution of the program. The keys of the dictionary are function objects, and the values are 4-element tuples representing the number of primitive calls, total call time, total relative call time, and recursion depth for each function.

  2. intermediate_stats: This element is a dictionary that provides intermediate statistics about the call stack. The keys of the dictionary are function objects, and the values are 3-element tuples representing the number of calls, total call time, and total relative call time for each function.

  3. function_calls: This element is a dictionary that provides information about the call stack during the time of the call. The keys of the dictionary are function objects, and the values are integers representing the number of calls made to each function.

  4. total_calls: This element is an integer that represents the total number of calls made during the execution of the program.

Example Usage

Here’s an example that demonstrates how to use sys.callstats():

import sys

def hello():
    print("Hello, world!")

def calculate_sum(a, b):
    return a + b

def main():
    result = calculate_sum(3, 5)
    hello()

    stats = sys.callstats()
    print(stats)

if __name__ == "__main__":
    main()

In this example, we define three functions: hello(), calculate_sum(), and main(). The main() function calculates the sum of two numbers using calculate_sum() and then calls hello(). After that, we use sys.callstats() to get the call statistics and print them.

When you run this code, you will see the call statistics outputted to the console:

{<function hello at 0x7fca7c228160>: (0, 0.0, 0.0, 0), 
 <function calculate_sum at 0x7fca7c2281f0>: (1, 0.0, 0.0, 0), 
 <function main at 0x7fca7c228280>: (0, 0.0, 0.0, 0)}

In this output, you can see that the hello() function and the calculate_sum() function were both called once, while the main() function was not called as it only contains the function calls. The values of total call time and relative call time are both 0.0 for all the functions, indicating that no timing information is available in this particular run.

Conclusion

The sys.callstats() function provides useful information about the call statistics of the Python interpreter. By analyzing this information, you can gain insights into the execution flow and performance of your Python program.