You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计代码中函数调用树的代码行数?求简便方法或插件

统计函数调用树总代码行数的方案

以下是几种实用的方案,覆盖工具插件和手动实现两种思路:

一、工具/插件方案

IDE集成工具

  • JetBrains系列IDE(PyCharm、IntelliJ等):
    右键目标函数选择「Show Call Hierarchy」打开调用树,再安装「Line Count」插件,选中调用树中所有相关节点,即可批量统计总代码行数。
  • VS Code:
    安装「Code Metrics」插件,它会自动分析函数调用关系并计算每个函数的代码行数,你可以在插件面板中筛选目标函数的调用树节点,直接查看行数总和。

命令行静态分析工具

  • 组合使用cloc(代码行数统计工具)和调用树生成工具:
    1. 用ctags或cscope生成项目的函数调用关系,导出目标函数的完整调用树列表(包含所有层级的被调用函数);
    2. 编写简单脚本过滤出这些函数所在的文件及行号范围;
    3. 用cloc针对筛选后的内容统计总行数。

二、手动实现思路(以Python为例)

如果需要定制化统计逻辑,可以自己写脚本实现,核心分为两步:统计单个函数行数、递归遍历调用树并去重。

核心逻辑示例

import inspect
import ast
import sys

def count_func_lines(func):
    """统计单个函数的代码行数"""
    try:
        source, start_line = inspect.getsourcelines(func)
        return len(source)
    except (TypeError, OSError):
        return 0  # 跳过内置函数、无法获取源码的函数

def get_called_funcs(func):
    """从函数源码中提取调用的本模块函数"""
    called_funcs = []
    module = sys.modules[func.__module__]
    try:
        source = inspect.getsource(func)
        tree = ast.parse(source)
        for node in ast.walk(tree):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
                func_name = node.func.id
                if hasattr(module, func_name):
                    called_obj = getattr(module, func_name)
                    if inspect.isfunction(called_obj):
                        called_funcs.append(called_obj)
        return called_funcs
    except Exception:
        return []

def calculate_call_tree_lines(func, visited=None):
    """递归统计调用树总行数,去重避免循环调用"""
    if visited is None:
        visited = set()
    func_id = id(func)
    if func_id in visited:
        return 0
    visited.add(func_id)
    
    total = count_func_lines(func)
    for called_func in get_called_funcs(func):
        total += calculate_call_tree_lines(called_func, visited)
    return total

# 使用示例
def foo():
    bar()
    return 1

def bar():
    baz()
    return 2

def baz():
    return 3

print(calculate_call_tree_lines(foo))  # 输出结果包含三个函数的总行数
  • 注意:这个脚本仅处理本模块内的函数调用,如果需要跨模块统计,需要扩展get_called_funcs逻辑,处理ast.Attribute类型的调用节点(比如module.func())。

内容的提问来源于stack exchange,提问作者Rodion Degtyar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:08:09