PCの負荷状況に合わせて、Webサイトでの処理を軽量なものに切り替えたい場合があります。
それを可能にする仕組みである「Compute Pressure API 」がChromeで実装が進められています。なお、仕様の方もW3Cで「Compute Pressure Level 1」が公開されています
例
Compute Pressure APIを使うと、PCのCPU負荷が4段階で確認できます。
- Nominal: 負荷が低い状態
- Fair: システムは正常に動作しており、追加のワークロードを実行できる
- Serious: 負荷が高い状態。追加のワークロードを実行するとCriticalになりうる
- Critical: 負荷が限界に近い状態
詳しいCPU情報はプライバシーの観点から公開しない設計になっています。
実行例
Compute Pressure API は現在Chromeの開発版で動作確認できます。
https://github.com/w3c/compute-pressure/blob/main/HOWTO.md を参考に実行しています。
サンプルでは、Observerを介して状態が変わる際にCallbackで負荷状態を出力しています。
function pressureObserverCallback(updates) { console.log("cpu pressure state = " + updates[0].state); console.log("timestamp = " + updates[0].time); } // Create observer with 1s sample rate. observer = new PressureObserver(pressureObserverCallback, { sampleRate: 1 }); // Start observer. await observer.observe("cpu");
実装のmemo
各 state の具体的なCPU使用率については仕様上では規定されていません。そこで、Chromeが実際にどのように判断しているかコードを一応確認しておきます。
今のところ、Nominal (30%未満), Fair (60%未満), Serious(90%未満), Critical (100%以下) となっているようです。ただし、より高度なアルゴリズムの利用も検討されているようですね。
// TODO(crbug.com/1342528): A more advanced algorithm that calculates // PressureState using PressureSample needs to be determined. // At this moment the algorithm is the simplest possible // with thresholds defining the state. mojom::PressureState state = mojom::PressureState::kN4ominal; if (sample.cpu_utilization < 0.3) state = mojom::PressureState::kNominal; else if (sample.cpu_utilization < 0.6) state = mojom::PressureState::kFair; else if (sample.cpu_utilization < 0.9) state = mojom::PressureState::kSerious; else if (sample.cpu_utilization <= 1.00) state = mojom::PressureState::kCritical; else NOTREACHED() << "unexpected value: " << sample.cpu_utilization;