撰寫規則時,最常見的效能陷阱是掃遍或複製從依附元件累積的資料。對整個建構作業進行匯總時,這些作業很容易要花費 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,確認是否有任何費用符合帳單規定。請避免將字串串連在一起,以免建構字串。最佳字串引數是常數,因為其記憶體會在規則的所有執行個體之間共用。
如果指令列中的引數過長,可以使用
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>
符號連結的父項。
效能分析
根據預設,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
:顯示建構作業的每秒 CPU 用量 (1 值代表 1 個核心的忙碌程度為 100%)。Critical Path
:針對重要路徑上的每個動作顯示一個區塊。grpc-command-1
:Bazel 的主要執行緒。有助於概略瞭解 Bazel 正在執行的工作,例如「Launch Bazel」、「評估 TargetPatterns」和「runAnalysisPhase」。Service Thread
:顯示小型和主要垃圾收集 (GC) 的停頓。
其他資料列代表 Bazel 執行緒,並顯示該執行緒中的所有事件。
常見效能問題
分析成效剖析資料時,請搜尋:
- 比預期分析階段 (
runAnalysisPhase
) 慢,尤其是在漸進式建構作業上。這可能代表規則實作不良,例如,扁平板的實作方式。套件載入作業可能會因為目標數量過多、複雜巨集或遞迴 glob 而慢慢載入。 - 每個慢速行動,尤其是在關鍵路徑上的動作。您也可以將大型動作分割為多個較小的動作,或減少 (遞移) 依附元件組合以加快執行速度。另請檢查異常的高非
PROCESS_TIME
值 (例如REMOTE_SETUP
或FETCH
)。 - 瓶頸是少數執行緒處於忙碌狀態,而所有其他會都在閒置 / 等待結果 (請見上方螢幕截圖中約 15 至 30 秒) 的情況。如要進行最佳化,很可能需要接觸規則實作或 Bazel 本身,以產生更多平行處理。如果 GC 數量異常,也會發生這種情況。
設定檔檔案格式
頂層物件包含中繼資料 (otherData
) 和實際的追蹤資料 (traceEvents
)。中繼資料包含叫用 ID 和 Bazel 叫用日期等額外資訊。
示例:
{
"otherData": {
"build_id": "101bff9a-7243-4c1a-8503-9dc6ae4c3b05",
"date": "Tue Jun 16 08:30:21 CEST 2020",
"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 追蹤事件格式規格。
analytics-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)
使用 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)