优化性能

报告问题 查看源代码

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

这很难理解,因此 Bazel 还提供了一个内存分析器,可帮助您找出可能出错的位置。注意:在广泛使用之前,编写低效规则的代价可能显而易见。

使用依赖项

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

depset 将信息表示为可实现共享的嵌套图表。

请参考下图:

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

每个节点会发布一个字符串。有了 depset,数据将如下所示:

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% 或更多。

以下是一些小窍门:

  • 直接将依赖项和列表作为参数传递,而不是自行展平。这些内容将在 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

传递操作输入应为 dset

使用 ctx.actions.run 构建操作时,不要忘记 inputs 字段会接受 depset。在以传递方式从依赖项收集输入时,使用此方法。

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 在调用期间花了多长时间非常有用。

--experimental_command_profile 标志可用于捕获各种类型的 Java 航班记录器配置文件(CPU 时间、实际用时、内存分配和锁争用)。

--starlark_cpu_profile 标志可用于编写所有 Starlark 线程 CPU 使用率的 pprof 配置文件。

内存分析

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)