优化性能

报告问题 查看源代码

在编写规则时,最常见的性能陷阱是遍历或复制从依赖项累积的数据。在整个构建过程中进行汇总时,这些操作很容易占用 O(N^2) 时间或空间。为避免这种情况,请务必了解如何有效使用依赖项。

这个过程可能不太容易理解,因此 Bazel 还提供了一个内存分析器,可以协助您找出可能出错的位置。注意:编写低效规则的成本在广泛使用之前可能不会显现。

使用依赖项

每当要汇总规则依赖项中的信息时,都应使用 depset。仅使用普通列表或字典来发布当前规则的本地信息。

depset 将信息表示为支持共享的嵌套图。

请参考下图:

C -> B -> A
D ---^

每个节点发布一个字符串。使用 depsets 时,数据如下所示:

a = depset(direct=['a'])
b = depset(direct=['b'], transitive=[a])
c = depset(direct=['c'], transitive=[b])
d = depset(direct=['d'], transitive=[b])

请注意,每个项目仅提及一次。使用列表,您将得到:

a = ['a']
b = ['b', 'a']
c = ['c', 'b', 'a']
d = ['d', 'b', 'a']

请注意,在本示例中,'a' 被提及了四次!如果图表较大,则问题只会变得更糟。

下面是一个规则实现示例,其中正确使用 Depset 来发布传递信息。请注意,如果需要,可以使用列表发布规则局部信息,因为这并不是 O(N^2)。

MyProvider = provider()

def _impl(ctx):
  my_things = ctx.attr.things
  all_things = depset(
      direct=my_things,
      transitive=[dep[MyProvider].all_things for dep in ctx.attr.deps]
  )
  ...
  return [MyProvider(
    my_things=my_things,  # OK, a flat list of rule-local things only
    all_things=all_things,  # OK, a depset containing dependencies
  )]

如需了解详情,请参阅依赖项概览页面。

避免调用 depset.to_list()

您可以使用 to_list() 将偏移量强制转换为扁平列表,但这样做通常会导致 O(N^2) 成本。如有可能,请避免出于调试目的对依赖项进行展平。

一个常见的误解是,如果您仅在顶级目标(例如 <xx>_binary 规则)中执行此操作,就可以自由扁平化废弃位置,因为这样一来,费用就不会在 build 图的每个层级上累计。但当您构建一组具有重叠依赖项的目标时,这仍然是 O(N^2)。构建测试 //foo/tests/... 或导入 IDE 项目时会发生这种情况。

减少对 depset 的调用次数

在循环中调用 depset 通常是错误的做法。它可能导致嵌套非常深的废弃,从而导致性能不佳。例如:

x = depset()
for i in inputs:
    # Do not do that.
    x = depset(transitive = [x, i.deps])

此代码可以轻松替换。首先,收集传递依赖项并一次性将其合并:

transitive = []

for i in inputs:
    transitive.append(i.deps)

x = depset(transitive = transitive)

这有时可以通过列表推导来减少:

x = depset(transitive = [i.deps for i in inputs])

针对命令行使用 ctx.actions.args()

构建命令行时,您应使用 ctx.actions.args()。这会将任何依赖项的扩展推迟到执行阶段。

除了能够提高严格程度之外,这还会减少规则的内存消耗,有时还会减少 90% 或更多。

下面提供了一些技巧:

  • 直接将 depset 和列表作为参数传递,而不是自行展平。这些内容将在 ctx.actions.args()之前为您展开。 如果您需要对嵌入内容进行任何转换,请查看 ctx.actions.args#add,看看是否有内容符合要求。

  • 您是否传递 File#path 作为实参?不需要。任何文件都会自动转换为其路径,并推迟到展开时间。

  • 避免通过将字符串连接在一起来构建字符串。 最佳字符串参数是一个常量,因为它的内存将由规则的所有实例共享。

  • 如果参数对于命令行而言过长,则可以使用 ctx.actions.args#use_param_file 有条件地或无条件地将 ctx.actions.args() 对象写入参数文件。此操作在执行操作时在后台完成。如果您需要明确控制参数文件,可以使用 ctx.actions.write 手动编写该文件。

例如:

def _impl(ctx):
  ...
  args = ctx.actions.args()
  file = ctx.declare_file(...)
  files = depset(...)

  # Bad, constructs a full string "--foo=<file path>" for each rule instance
  args.add("--foo=" + file.path)

  # Good, shares "--foo" among all rule instances, and defers file.path to later
  # It will however pass ["--foo", <file path>] to the action command line,
  # instead of ["--foo=<file_path>"]
  args.add("--foo", file)

  # Use format if you prefer ["--foo=<file path>"] to ["--foo", <file path>]
  args.add(format="--foo=%s", value=file)

  # Bad, makes a giant string of a whole depset
  args.add(" ".join(["-I%s" % file.short_path for file in files])

  # Good, only stores a reference to the depset
  args.add_all(files, format_each="-I%s", map_each=_to_short_path)

# Function passed to map_each above
def _to_short_path(f):
  return f.short_path

传递操作输入应为 depset

使用 ctx.actions.run 构建操作时,请记得 inputs 字段接受一个偏移量。在以传递方式从依赖项收集输入时,请使用此方法。

inputs = depset(...)
ctx.actions.run(
  inputs = inputs,  # Do *not* turn inputs into a list
  ...
)

悬挂式

如果 Bazel 似乎挂起,您可以按 Ctrl-\ 或向 Bazel 发送 SIGQUIT 信号 (kill -3 $(bazel info server_pid)),以获取文件 $(bazel info output_base)/server/jvm.out 中的线程转储。

如果 bazel 挂起,您可能无法运行 bazel info,因此 output_base 目录通常是工作区目录中 bazel-<workspace> 符号链接的父级。

性能剖析

JSON 跟踪记录配置文件对于快速了解 Bazel 在调用过程中花费的时间非常有用。

内存性能分析

Bazel 附带内置的内存分析器,可帮助您检查规则的内存用量。如果出现问题,您可以转储堆,找到导致问题的确切代码行。

启用内存跟踪

您必须将以下两个启动标志传递给每次 Bazel 调用

  STARTUP_FLAGS=\
  --host_jvm_args=-javaagent:<path to java-allocation-instrumenter-3.3.0.jar> \
  --host_jvm_args=-DRULE_MEMORY_TRACKER=1

这些操作会以内存跟踪模式启动服务器。如果您忘记了这些步骤,即使是在一次 Bazel 调用中,服务器也会重启,而且您必须重新开始。

使用内存跟踪器

例如,查看目标 foo 并了解其用途。如果只想运行分析,而不运行构建执行阶段,请添加 --nobuild 标志。

$ bazel $(STARTUP_FLAGS) build --nobuild //foo:foo

接下来,查看整个 Bazel 实例消耗的内存量:

$ bazel $(STARTUP_FLAGS) info used-heap-size-after-gc
> 2594MB

使用 bazel dump --rules 按规则类对其进行细分:

$ bazel $(STARTUP_FLAGS) dump --rules
>

RULE                                 COUNT     ACTIONS          BYTES         EACH
genrule                             33,762      33,801    291,538,824        8,635
config_setting                      25,374           0     24,897,336          981
filegroup                           25,369      25,369     97,496,272        3,843
cc_library                           5,372      73,235    182,214,456       33,919
proto_library                        4,140     110,409    186,776,864       45,115
android_library                      2,621      36,921    218,504,848       83,366
java_library                         2,371      12,459     38,841,000       16,381
_gen_source                            719       2,157      9,195,312       12,789
_check_proto_library_deps              719         668      1,835,288        2,552
... (more output)

使用 bazel dump --skylark_memory 生成 pprof 文件以查看内存的存储位置:

$ bazel $(STARTUP_FLAGS) dump --skylark_memory=$HOME/prof.gz
> Dumping Starlark heap to: /usr/local/google/home/$USER/prof.gz

使用 pprof 工具调查堆。一个很好的起点是使用 pprof -flame $HOME/prof.gz 获取火焰图。

https://github.com/google/pprof 获取 pprof

获取用以下行注释的最热门调用站点的文本转储:

$ pprof -text -lines $HOME/prof.gz
>
      flat  flat%   sum%        cum   cum%
  146.11MB 19.64% 19.64%   146.11MB 19.64%  android_library <native>:-1
  113.02MB 15.19% 34.83%   113.02MB 15.19%  genrule <native>:-1
   74.11MB  9.96% 44.80%    74.11MB  9.96%  glob <native>:-1
   55.98MB  7.53% 52.32%    55.98MB  7.53%  filegroup <native>:-1
   53.44MB  7.18% 59.51%    53.44MB  7.18%  sh_test <native>:-1
   26.55MB  3.57% 63.07%    26.55MB  3.57%  _generate_foo_files /foo/tc/tc.bzl:491
   26.01MB  3.50% 66.57%    26.01MB  3.50%  _build_foo_impl /foo/build_test.bzl:78
   22.01MB  2.96% 69.53%    22.01MB  2.96%  _build_foo_impl /foo/build_test.bzl:73
   ... (more output)