最佳化效能

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

要正確執行操作可能並不容易,因此 Bazel 也會提供記憶體分析器,以助您找出自己可能犯錯的地方。請留意:在廣泛使用之前,編寫效率低落的規則可能付出代價。

使用 depset

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

虛設常式以巢狀結構圖表示資訊,允許共用。

請參考以下圖表:

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' 會提及 4 次!而如果圖表較大,這個問題只會越來越嚴重。

以下範例中的規則導入使用正確解碼來發布遞移資訊。請注意,您可以視需要使用清單發布規則本機資訊,因為這不是 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) 成本。如果可以,請盡量避免為了偵錯目的而分割空白集。

常見的誤解是,如果只在頂層目標 (例如 <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%。

以下提供幾個訣竅:

  • 直接將依附元件和清單做為引數傳遞,而不是自行整併。這些項目將由 ctx.actions.args() 為你展開。 如果需要對記憶體不足內容進行轉換,請查看 ctx.actions.args#add,確認是否有任何費用符合帳單大小。

  • 您是否將 File#path 做為引數傳遞?不需要。任何檔案都會自動轉換為其「路徑」,並延後到展開時間。

  • 串連不同字串,以免建構字串。最佳字串引數是常數,因為系統會在規則的所有執行個體之間共用其記憶體。

  • 如果指令列的引數過長,ctx.actions.args() 物件可能會有條件或者無條件使用 ctx.actions.args#use_param_file 寫入參數檔案。這會在動作執行時於背景執行。如需明確控制參數檔案,可以使用 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> 符號連結的父項。

效能分析

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

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

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

  • 按下 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 正在執行的作業,例如「Launch Bazel」、「valuTargetPatterns」和「runAnalysisPhase」。
  • Service Thread:顯示輕微的垃圾收集 (GC) 暫停情形。

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

常見效能問題

分析成效設定檔時,請注意以下幾點:

  • 低於預期的分析階段 (runAnalysisPhase),尤其是漸進式建構作業。這可能表示規則實作方式不佳,例如,規則實作方式過於平滑。套件載入速度可能會因為目標數量過多、巨集或遞迴 glob 而變慢。
  • 個別執行速度緩慢的動作,尤其是關鍵路徑上的動作。您可以將大型動作分割為多個較小的動作,或是減少一組 (遞移) 依附元件以加快執行速度。此外,請檢查是否有異常的高度非 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 追蹤事件格式規格

分析設定檔

這個剖析方法包含兩個步驟,您必須先使用 --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)

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