Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

使用报告信息对象计算代码行数

此示例说明如何使用报告信息对象计算源代码和生成代码中的行数。有关报告信息对象的详细信息,请参阅Access Code Generation Report Information Programmatically

MATLAB 代码

在此示例中,您将为 MATLAB 函数 dijkstra 生成代码。此函数使用 Dijkstra 算法计算从节点到图中每个其他节点的最短路径的长度。

type dijkstra
% DIJKSTRA Find length of shortest path between nodes in a graph
%
% D = dijkstra(A, p) 
% Takes a graph represented by its adjacency matrix 'A' along with a node 
% 'p' as input and returns a vector 'D' containing the length of the 
% shortest path from 'p' to all other nodes in the graph. 

% Copyright 2018 The MathWorks, Inc.
function D = dijkstra(A, p) %#codegen

    narginchk(2,2);
    
    [m, n] = size(A);

    % Assertions to make sure inputs are valid
    assert(m == n, "Input adjacency matrix for graph must be a square matrix");
    assert(rem(p, 1) == 0 && p <= m && p > 0, "Input src must be a node in the graph");
    
    % Initialization
    max = realmax;
    D = repmat(max, 1, m);
    D(p) = 0;
    visited = false(1, m);
    
    for i = 1:m
        % Select next node to visit
        min = max;
        u = -1;
        for v = 1:n
            if ~visited(v) && D(v) <= min
                min = D(v);
                u = v;
            end
        end
        
        % Mark selected node as visited
        visited(u) = true;
        
        %{ 
          Update distances of nodes adjacent to selected node that are yet
          to be visited
        %}
        for v = 1:n
            if(~visited(v) && A(u, v) ~= 0 && D(u) ~= max)
                distVal = D(u) + A(u, v);
                if distVal < D(v)
                    D(v) = distVal;
                end
            end
        end
    end
end

指定一个图的邻接矩阵 A 和遍历该图的开始节点 p。绘制图。调用 dijkstra 以计算从 p 到图中每个节点的最短距离,并显示这些距离。

% Sample adjacency Matrix for graph with 5 nodes
A = [
        0 1 1 0 0; 
        1 0 0 1 1; 
        1 0 0 1 0; 
        0 1 1 0 1; 
        0 1 0 1 0
    ];

% Plot the graph to see how it looks like
G = graph(A, 'omitselfloops');
plot(G, 'EdgeLabel', G.Edges.Weight)

Figure contains an axes object. The axes object contains an object of type graphplot.

% Source node from where graph traversal begins
p = randi(size(A, 1));

% Calculate shortest distance from 'p' to every other node in graph G
D = dijkstra(A, p);

for i=1:numel(D)
    fprintf("Length of shortest path from %d to %d is %d. \n", p, i, D(i));
end
Length of shortest path from 5 to 1 is 2. 
Length of shortest path from 5 to 2 is 1. 
Length of shortest path from 5 to 3 is 2. 
Length of shortest path from 5 to 4 is 1. 
Length of shortest path from 5 to 5 is 0. 

导出有关代码生成的信息

报告信息对象提供对代码生成相关信息的编程访问。此对象的属性提供有关代码生成设置、输入文件、生成的文件以及代码生成错误、警告和信息消息的信息。

要将报告信息对象导出到 MATLAB 基础工作区中的变量,请在运行 codegen 命令时在变量名称中包含 -reportinfo 选项。在此示例中,您将代码生成报告信息导出为变量 info

codegen -c dijkstra -args {A, p} -reportinfo info
Code generation successful.

计算代码行数

loc 函数将报告信息对象作为输入,并返回两个输出,分别包含源代码和生成代码中的行数。此函数在计算代码行数时排除空行和包括注释的行。

type loc
% LOC Calculate total lines of source and generated code in a codegen run
%
% [i, o] = loc(r) 
% Takes a report information object 'r' as input, and produces two
% outputs - 'i' and 'o' containing the total lines of code in the source
% MATLAB files and generated files respectively.

% Copyright 2018 The MathWorks, Inc.
function [i, o] = loc(r)
    narginchk(1,1);

    % Assert that input is a report information object.
    assert(isa(r, 'coder.ReportInfo'), 'Input must be of type coder.ReportInfo');

    % Fetch source and generated files from the report information object.
    sourceFiles = r.InputFiles;
    generatedFiles = r.GeneratedFiles;
    
    % Count lines of code in source and generated files. Blank lines, and
    % comments are not counted.
    i = countLines(sourceFiles, true);
    o = countLines(generatedFiles, false);
end

function count = countLines(files, isSource)
    count = 0;
    for i=1:numel(files)
        f = files(i);
        if isprop(f, 'Text')
            lines = splitlines(f.Text);
            for j=1:numel(lines)
                line = strtrim(lines{j});
                if ~isempty(line) && ~isComment(line, isSource)
                    count = count + 1;
                end
            end
            clear isComment; % clear persistent variables
        end
    end
end

function result = isComment(line, isSource)
    persistent inBlockComment;
    if isempty(inBlockComment)
        inBlockComment = false;
    end
    if isSource
        result = (startsWith(line, "%") || inBlockComment);
        if line == "%{" || line == "%}"
            inBlockComment = (line ~= "%}");
        end
    else
        result = (startsWith(line, "/") || inBlockComment);
        if startsWith(line, "/*") || endsWith(line, "*/")
            inBlockComment = ~endsWith(line, "*/");
        end
    end
end

以报告信息对象 info 作为输入来调用 loc。显示源文件和生成文件中的代码行数。

info = evalin('base', 'info');
[nLocIn, nLocOut] = loc(info);
fprintf('Lines of code in source MATLAB file(s): %d', nLocIn);
Lines of code in source MATLAB file(s): 29
fprintf('Lines of code in generated file(s): %d', nLocOut);
Lines of code in generated file(s): 581

另请参阅

相关主题