最佳化效能

回報問題 查看來源

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

這可能難以正確執行,因此 Bazel 也提供記憶體分析器,協助您找出可能出錯的地方。警告: 編寫效率不佳規則的成本,必須廣泛使用,才能發現成本。

使用 depset

每當您從規則依附元件匯總資訊時,都應使用 depset。請僅使用純清單或字典,將資訊發布至目前規則的本機資訊。

解碼器會以巢狀結構圖的形式呈現資訊,方便使用者共用。

請參考以下圖表:

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

每個節點都會發布單一字串。解碼後,資料看起來會像這樣:

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'!圖表較大時,這個問題只會越來越嚴重

以下為正確使用解碼設定來發布遞移資訊的規則實作範例。請注意,您可以視需要使用清單發布規則本機資訊,因為這不是 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() 強制將 dep 設為平面清單,但這樣做通常會導致 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()。這會延後展開至執行階段的任何解碼器。

除了加快速度以外,這也能減少規則的記憶體用量,有時甚至可減少 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

遞移動作輸入內容應為解壓縮

使用 ctx.actions.run 建構動作時,請勿忘記 inputs 欄位接受解碼。如果輸入內容是從依附元件傳遞而來,請使用這個方法。

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)