简体   繁体   中英

Using javascript to detect device CPU/GPU performance?

(The question is not specific to three.js but I will use it as an example)

I have been using three.js to develop a web app interface lately and written some nice fallback between WebGL and Canvas renderer (for desktop browsers).

But now the problem becomes how to properly detect device capability, there are 2 aspects to the problem:

  1. browser features (static features like webgl/canvas): this is largely solved within web community using simple feature detect.
  2. device capability : this is the hard part, without direct access to device's hardware information, we need some ways of telling whether we should fallback to less hardware-demanding code.

A notable example : Firefox mobile/Opera mobile claims support of WebGL but are buggy or limited by device hardware.

A few workarounds I come up with so far:

  1. Use a common feature as performance indicator - touch device, for example, has less powerful hardware in general. The con: it's not future-proof.
  2. Blacklist known buggy browser/device - UA sniffing will be unavoidable, and it can be hard to maintain.
  3. Performance test - hence the question, besides running the code and measure framerate, are there better options?

Or maybe it doesn't have to be this hard, are there other suggestions?

I've ended up using a performance measurement approach on a project where we wanted to utilise canvas features that are available on high spec CPU/GPU desktops, as well as lower speed devices such as tables and phones.

Basically we start at a minimum scene complexity, and if the renderloop takes less than 33ms we add complexity (we also reduce complexity if the renderloop starts taking too long at a later time).

I suppose in your case you might have to run a quick canvas and webgl performance test and then choose one. Having spent some time researching this I've not come across some tricky non-obvious technique that solves this better.

您可以使用http://webglstats.com/进行WebGL硬件支持和功能检测。

If your using three.js you can just use the detector.js to find out if webgl is enabled. also staying away from the canvasrenderer will help. use the webglrenderer or the softwarerender. as they allow for more vertices. the softwarerender is fairly new and needs some work but can be used.

This is the snippet I wrote to benchmark webgl, using three.js:

import {
  Mesh,
  MeshStandardMaterial,
  PerspectiveCamera,
  Scene,
  SphereGeometry,
  WebGLRenderer,
} from "three";

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export enum GPUPerformanceLevel {
  HIGH = "HIGH",
  LOW = "LOW",
}

/**
 * Three.js based webgl benchmark
 *
 * In summary, the `run` method adds `meshPerStep` new spheres every step (frame)
 * and measures the fps. If we're able to perform >=`thresholds.steps` of these
 * steps, without the fps dropping below `thresholds.fps`, then we label the device
 * `GPUPerformanceLevel.HIGH`.
 */
export class GPUBenchmark {
  scene = new Scene();
  material = new MeshStandardMaterial();
  geometry = new SphereGeometry();

  static thresholds = { fps: 10, steps: 40 };
  static meshPerStep = 1000;

  async run(debug = false): Promise<GPUPerformanceLevel> {
    const camera = new PerspectiveCamera(75);
    const renderer = new WebGLRenderer();

    let tPrev = performance.now() / 1000;
    let steps = 0;

    let passedThreshold = false;

    const animate = async () => {
      const time = performance.now() / 1000;
      const fps = 1 / (time - tPrev);
      tPrev = time;

      if (debug) {
        console.log(`fps: ${fps} steps: ${steps}`);
      }

      if (
        fps > GPUBenchmark.thresholds.fps &&
        steps < GPUBenchmark.thresholds.steps
      ) {
        requestAnimationFrame(animate);

        this.step();
        steps++;
        renderer.render(this.scene, camera);
      } else {
        passedThreshold = true;
      }
    };

    animate();

    while (!passedThreshold) {
      await sleep(1);
    }

    this.cleanup();
    const level = GPUBenchmark.stepsToPerfLevel(steps);

    if (debug) {
      console.log("device benchmarked at level:", level);
    }

    return level;
  }

  private step() {
    for (let i = 0; i < GPUBenchmark.meshPerStep; i++) {
      const sphere = new Mesh(this.geometry, this.material);
      sphere.frustumCulled = false;

      this.scene.add(sphere);
    }
  }

  private cleanup() {
    for (const obj of this.scene.children) {
      this.scene.remove(obj);
    }

    //@ts-ignore
    this.scene = null;

    this.material.dispose();
    this.geometry.dispose();

    //@ts-ignore
    this.material = null;
    //@ts-ignore
    this.geometry = null;
  }

  private static stepsToPerfLevel(numSteps: number): GPUPerformanceLevel {
    if (numSteps >= GPUBenchmark.thresholds.steps) {
      return GPUPerformanceLevel.HIGH;
    } else {
      return GPUPerformanceLevel.LOW;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM