最佳化效能

回報問題 查看來源

編寫規則時,最常見的效能問題是掃遍或複製從依附元件累積的資料。在整個建構作業中進行匯總時,這些作業很容易使用 O(N^2) 時間或空間。為避免這種情況,請務必瞭解如何有效使用 depset。

這可能很難正確做出,因此 Bazel 也提供記憶體分析器,可協助找出可能出錯的位置。警告: 編寫低效率規則的成本可能要等到廣泛使用後才能顯現。

使用解碼器

每當您要從規則依附元件取得資訊時,請使用 depsets。請只使用純清單或字典,將本機資訊發布至目前規則。

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' 被提及 4 次!隨著圖形較大,這個問題只會越來越嚴重。

以下是規則實作範例,正確使用 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 總覽頁面。

避免撥打 depset.to_list()

您可以使用 to_list() 將依附元件強制轉換為平面清單,但這麼做通常會產生 O(N^2) 費用。如果可以,請盡量避免為了偵錯目的而簡化依附元件。

常見的誤解是,如果您只是在頂層目標 (例如 <xx>_binary 規則) 執行依附元件,就可以自由壓平解碼器,因為這樣系統就不會累計建構圖表的每個層級的費用。但當您建構一組具有重疊依附元件的目標時,這種做法仍然 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(),這樣會將任何 Depset 擴展至執行階段。

除了速度更快,這項做法可降低規則的記憶體消耗量 (有時可降低 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

遞移動作輸入內容應為解碼器

使用 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 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)