最佳化效能

回報問題 查看來源 Nightly · 8.3 · 8.2 · 8.1 · 8.0 · 7.6

撰寫規則時,最常見的效能陷阱是遍歷或複製從依附元件累積的資料。如果匯總整個建構作業,這些作業很容易就會耗費 O(N^2) 的時間或空間。為避免這種情況,請務必瞭解如何有效使用 depsets。

這項作業可能很難正確完成,因此 Bazel 也提供記憶體剖析器,協助您找出可能出錯的地方。警告: 低效率規則的成本可能要到廣泛使用後才會顯現。

使用 depsets

從規則依附元件匯總資訊時,請一律使用 depset。只能使用純清單或字典,發布目前規則的本機資訊。

depsset 會以巢狀圖的形式呈現資訊,方便您分享。

請參考下圖:

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' 出現了四次!圖表越大,這個問題就越嚴重。

以下是規則實作範例,其中正確使用 depsets 發布遞移資訊。請注意,如果您想使用清單發布規則本機資訊,是可以的,因為這不是 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() 強制將 depset 轉換為扁平清單,但這麼做通常會導致 O(N^2) 成本。如果可以,請避免將 depsets 扁平化,除非是為了偵錯。

一般常見的誤解是,如果只在頂層目標 (例如 <xx>_binary 規則) 中執行此操作,您就可以隨意扁平化 depsets,因為這樣一來,費用就不會累積在建構圖的每個層級。但如果建構一組具有重疊依附元件的目標,這仍然是 O(N^2)。建構測試 //foo/tests/... 或匯入 IDE 專案時,就會發生這種情況。

減少對 depset 的呼叫次數

在迴圈內呼叫 depset 通常是錯誤的做法。這可能會導致巢狀結構非常深的 depsets,效能不佳。例如:

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

這個代碼可以輕鬆替換。首先,請收集遞移 depsets,然後一次合併所有 depsets:

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()。這會將任何 depsets 的擴充作業延後至執行階段。

除了速度更快之外,這也會減少規則的記憶體耗用量,有時甚至可減少 90% 以上。

以下提供幾個訣竅:

  • 請直接將 depsets 和清單做為引數傳遞,而不是自行將其扁平化。ctx.actions.args() 會為你擴充這些主題。 如果需要對 deps 集合內容進行任何轉換,請查看 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

遞移動作輸入內容應為 depsets

使用 ctx.actions.run 建構動作時,請勿忘記 inputs 欄位接受 depset。只要是從依附元件遞移收集輸入內容,就請使用這項功能。

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

懸掛

如果 Bazel 似乎停止回應,您可以按下 Ctrl-\ 鍵,或傳送 SIGQUIT 信號 (kill -3 $(bazel info server_pid)) 給 Bazel,在 $(bazel info output_base)/server/jvm.out 檔案中取得執行緒傾印。

如果 Bazel 停止回應,您可能無法執行 bazel info,因此 output_base 目錄通常是工作區目錄中 bazel-<workspace> 符號連結的父項。

效能分析

根據預設,Bazel 會將 JSON 設定檔寫入輸出基底的 command.profile.gz。您可以使用 --profile 標記設定位置,例如 --profile=/tmp/profile.gz。結尾為 .gz 的位置會以 GZIP 壓縮。

如要查看結果,請在 Chrome 瀏覽器分頁中開啟 chrome://tracing,然後按一下「載入」並選取 (可能經過壓縮的) 設定檔。如要查看更詳細的結果,請按一下左下角的方塊。

你可以使用下列鍵盤控制項進行瀏覽:

  • 按下 1 進入「選取」模式。在這個模式下,您可以選取特定方塊,檢查事件詳細資料 (請參閱左下角)。選取多個事件,即可查看摘要和匯總統計資料。
  • 按下 2 進入「平移」模式。接著拖曳滑鼠即可移動檢視畫面。你也可以使用 a/d 鍵向左/右移動。
  • 按下 3 進入「縮放」模式。然後拖曳滑鼠即可縮放。你也可以使用 w/s 放大/縮小。
  • 按下 4 進入「計時」模式,即可測量兩個事件之間的距離。
  • 按下 ? 即可瞭解所有控制項。

個人資訊

範例設定檔:

範例設定檔

圖 1. 範例設定檔。

以下是幾個特殊資料列:

  • action counters:顯示目前有多少並行動作正在進行。按一下即可查看實際值。應高於乾淨建構中的 --jobs 值。
  • cpu counters:顯示 Bazel 在建構期間每秒使用的 CPU 數量 (值為 1 等於一個核心 100% 忙碌)。
  • Critical Path:針對重要路徑上的每個動作顯示一個方塊。
  • grpc-command-1:Bazel 的主要執行緒。有助於瞭解 Bazel 的運作方式,例如「啟動 Bazel」、「evaluateTargetPatterns」和「runAnalysisPhase」。
  • Service Thread:顯示次要和主要垃圾收集 (GC) 暫停。

其他列代表 Bazel 執行緒,並顯示該執行緒上的所有事件。

常見效能問題

分析效能設定檔時,請注意下列事項:

  • 分析階段 (runAnalysisPhase) 比預期慢,尤其是增量建構。這可能表示規則實作不佳,例如將 depsets 扁平化。如果目標數量過多、巨集複雜或全域模式遞迴,套件載入速度可能會很慢。
  • 個別緩慢的動作,尤其是重要路徑上的動作。您可以將大型動作拆分成多個較小的動作,或減少 (遞移) 依附元件的集合,藉此加快動作速度。此外,也請檢查是否有異常高的非 PROCESS_TIME 值 (例如 REMOTE_SETUPFETCH)。
  • 瓶頸,也就是少數執行緒正忙碌,而其他執行緒都處於閒置狀態 / 等待結果 (請參閱上方螢幕截圖中 15 秒到 30 秒左右)。如要進行最佳化,您可能需要觸及規則實作或 Bazel 本身,以導入更多平行處理。如果發生異常大量的垃圾收集事件,也可能導致這種情況。

設定檔格式

頂層物件包含中繼資料 (otherData) 和實際追蹤資料 (traceEvents)。中繼資料包含額外資訊,例如叫用 ID 和 Bazel 叫用日期。

範例:

{
  "otherData": {
    "build_id": "101bff9a-7243-4c1a-8503-9dc6ae4c3b05",
    "date": "Tue Jun 16 08:30:21 CEST 2020",
    "profile_finish_ts": "1677666095162000",
    "output_base": "/usr/local/google/_bazel_johndoe/573d4be77eaa72b91a3dfaa497bf8cd0"
  },
  "traceEvents": [
    {"name":"thread_name","ph":"M","pid":1,"tid":0,"args":{"name":"Critical Path"}},
    {"cat":"build phase marker","name":"Launch Bazel","ph":"X","ts":-1824000,"dur":1824000,"pid":1,"tid":60},
    ...
    {"cat":"general information","name":"NoSpawnCacheModule.beforeCommand","ph":"X","ts":116461,"dur":419,"pid":1,"tid":60},
    ...
    {"cat":"package creation","name":"src","ph":"X","ts":279844,"dur":15479,"pid":1,"tid":838},
    ...
    {"name":"thread_name","ph":"M","pid":1,"tid":11,"args":{"name":"Service Thread"}},
    {"cat":"gc notification","name":"minor GC","ph":"X","ts":334626,"dur":13000,"pid":1,"tid":11},

    ...
    {"cat":"action processing","name":"Compiling third_party/grpc/src/core/lib/transport/status_conversion.cc","ph":"X","ts":12630845,"dur":136644,"pid":1,"tid":1546}
 ]
}

追蹤事件中的時間戳記 (ts) 和時間長度 (dur) 皆以微秒為單位。類別 (cat) 是 ProfilerTask 的其中一個列舉值。 請注意,如果某些事件很短且彼此接近,系統會將這些事件合併;如要避免合併事件,請傳遞 --noslim_json_profile

另請參閱「Chrome 追蹤事件格式規格」。

analyze-profile

這個剖析方法包含兩個步驟,首先您必須使用 --profile 標記執行建構/測試,例如

$ bazel build --profile=/tmp/prof //path/to:target

產生的檔案 (本例中為 /tmp/prof) 是二進位檔案,可透過 analyze-profile 指令進行後續處理和分析:

$ bazel analyze-profile /tmp/prof

根據預設,這項工具會列印指定設定檔資料檔案的摘要分析資訊。包括每個建構階段不同工作類型的累計統計資料,以及重要路徑的分析。

預設輸出的第一節是不同建構階段所花時間的總覽:

INFO: Profile created on Tue Jun 16 08:59:40 CEST 2020, build ID: 0589419c-738b-4676-a374-18f7bbc7ac23, output base: /home/johndoe/.cache/bazel/_bazel_johndoe/d8eb7a85967b22409442664d380222c0

=== PHASE SUMMARY INFORMATION ===

Total launch phase time         1.070 s   12.95%
Total init phase time           0.299 s    3.62%
Total loading phase time        0.878 s   10.64%
Total analysis phase time       1.319 s   15.98%
Total preparation phase time    0.047 s    0.57%
Total execution phase time      4.629 s   56.05%
Total finish phase time         0.014 s    0.18%
------------------------------------------------
Total run time                  8.260 s  100.00%

Critical path (4.245 s):
       Time Percentage   Description
    8.85 ms    0.21%   _Ccompiler_Udeps for @local_config_cc// compiler_deps
    3.839 s   90.44%   action 'Compiling external/com_google_protobuf/src/google/protobuf/compiler/php/php_generator.cc [for host]'
     270 ms    6.36%   action 'Linking external/com_google_protobuf/protoc [for host]'
    0.25 ms    0.01%   runfiles for @com_google_protobuf// protoc
     126 ms    2.97%   action 'ProtoCompile external/com_google_protobuf/python/google/protobuf/compiler/plugin_pb2.py'
    0.96 ms    0.02%   runfiles for //tools/aquery_differ aquery_differ

記憶體用量分析

Bazel 內建記憶體分析器,可協助您檢查規則的記憶體用量。如有問題,您可以傾印堆積,找出造成問題的確切程式碼行。

啟用記憶體追蹤功能

您必須將這兩個啟動標記傳遞至每個 Bazel 叫用:

  STARTUP_FLAGS=\
  --host_jvm_args=-javaagent:$(BAZEL)/third_party/allocation_instrumenter/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)

產生 pprof 檔案,瞭解記憶體用量:bazel dump --skylark_memory

$ 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)