stats.js源码解读

1,326 阅读3分钟

github 地址:https://github.com/mrdoob/stats.js/blob/master/src/Stats.js

1.性能监控

  • FPS 在最近一秒渲染的帧数量。数值越高,性能越好.
  • MS 渲染帧所需的毫秒数。数值越低,性能越好.
  • MB 占用的内存大小. (Chrome 浏览器快捷键后面添加--enable-precise-memory-info 命令)

2.fps 计算

var fps = 0;
var prevTime = (performance || Date).now(),
  frames = 0;
function aaa() {
  frames++;

  var time = (performance || Date).now();
  //每秒计算一次渲染帧数量
  if (time >= prevTime + 1000) {
    fps = (frames * 1000) / (time - prevTime);
    console.log(fps);
    prevTime = time;
    frames = 0;
  }
  window.requestAnimationFrame(aaa);
}
aaa();

3.ms 每个渲染帧运行需要多少毫秒

let ms = 0;
var beginTime = (performance || Date).now();
function bbb() {
  //当前时间减去开始时间
  ms = (performance || Date).now() - beginTime;
  console.log(ms);
  window.requestAnimationFrame(bbb);
  beginTime = (performance || Date).now();
}
bbb();

4.memory 内存占用

usedJSHeapSize已经使用的内存

jsHeapSizeLimit内存大小限制

let mb = 0,
  mbPercent = 0;
let prevTime = (performance || Date).now();
function ccc() {
  var time = (performance || Date).now();
  //每秒获取一次
  if (time >= prevTime + 1000) {
    //获取性能里的内存相关参数,前提是performance.memory存在
    var memory = performance.memory;
    //1M =1048576=2^20
    //使用了多少内存
    mb = memory.usedJSHeapSize / 1048576;
    //内存占用百分比
    mbPercent = memory.usedJSHeapSize / memory.jsHeapSizeLimit;
    console.log(mb, mbPercent);
  }
  window.requestAnimationFrame(ccc);
}
ccc();

5.画 Canvas 的板面

创建 canvas

//name性能名称, fg颜色, bg背景
Stats.Panel = function (name, fg, bg) {
  var min = Infinity,
    max = 0,
    round = Math.round;
  var PR = round(window.devicePixelRatio || 1);

  var WIDTH = 80 * PR, //canvas板面宽度
    HEIGHT = 48 * PR, //canvas板面高度
    TEXT_X = 3 * PR, //文本x坐标
    TEXT_Y = 2 * PR, //文本y坐标
    GRAPH_X = 3 * PR, //图表x坐标
    GRAPH_Y = 15 * PR, //图表y坐标
    GRAPH_WIDTH = 74 * PR, //图表宽度
    GRAPH_HEIGHT = 30 * PR; //图表高度

  //创建canvas
  var canvas = document.createElement('canvas');
  canvas.width = WIDTH;
  canvas.height = HEIGHT;
  canvas.style.cssText = 'width:80px;height:48px';

  var context = canvas.getContext('2d');
  //设置字体样式
  context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  context.textBaseline = 'top';
};

板面更新数值



update:function (value, maxValue) {
//监控过程中,最小最大值范围
      min = Math.min(min, value);
      max = Math.max(max, value);

      context.fillStyle = bg;
      context.globalAlpha = 1;
      //清空内容重绘
      context.fillRect(0, 0, WIDTH, GRAPH_Y);
      context.fillStyle = fg;
      //画文本,当前数值,name,最小最大值
      context.fillText(
        round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')',
        TEXT_X,
        TEXT_Y
      );
    //截取canvas之前的内容范围,往前移动,覆盖内容
      context.drawImage(
        canvas,
        GRAPH_X + PR,
        GRAPH_Y,
        GRAPH_WIDTH - PR,
        GRAPH_HEIGHT,
        GRAPH_X,
        GRAPH_Y,
        GRAPH_WIDTH - PR,
        GRAPH_HEIGHT
      );
    //清空最后的那部分
      context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);

      context.fillStyle = bg;
      context.globalAlpha = 0.9;
      //画出最新的数值矩形
      context.fillRect(
        GRAPH_X + GRAPH_WIDTH - PR,
        GRAPH_Y,
        PR,
        round((1 - value / maxValue) * GRAPH_HEIGHT)
      );
    }

6.创建 Stats 板面

var mode = 0;

var container = document.createElement('div');
container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
//点击切换板面模式
container.addEventListener(
  'click',
  function (event) {
    event.preventDefault();
    showPanel(++mode % container.children.length);
  },
  false
);

//添加canvas板面
function addPanel(panel) {
  container.appendChild(panel.dom);
  return panel;
}
//显示对应的板面模式
function showPanel(id) {
  for (var i = 0; i < container.children.length; i++) {
    container.children[i].style.display = i === id ? 'block' : 'none';
  }

  mode = id;

添加三种 canvas 板面

//添加索引为0的fps板面
var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
//添加索引为1的ms板面
var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
//如果performance.memory存在,添加索引为2的内存板面
if (self.performance && self.performance.memory) {
  var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
}
//默认显示fps
showPanel(0);

每个板面数值的更新

  var beginTime = (performance || Date).now(),
    prevTime = beginTime,
    frames = 0;
//开始时间
begin: function () {
      beginTime = (performance || Date).now();
    },
//计算
    end: function () {
      frames++;

      var time = (performance || Date).now();
    //ms板面的数值
      msPanel.update(time - beginTime, 200);

      if (time >= prevTime + 1000) {
        //fps板面数值
        fpsPanel.update((frames * 1000) / (time - prevTime), 100);

        prevTime = time;
        frames = 0;
        //内存板面数值更新
        if (memPanel) {
          var memory = performance.memory;
          //1M =1048576=2^20
          memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
        }
      }

      return time;
    },
//更新
    update: function () {
      beginTime = this.end();
    },

7.使用 Stats

var stats = new Stats();
document.body.appendChild(stats.dom);
function animate() {
  stats.update();
  window.requestAnimationFrame(animate);
}
animate();

总结

Stats 真的很小巧实用,不用打开开发者中心,就可以用于监控界面性能,比如可视化大屏或者一些复杂界面的性能,点开某个功能,猛地飙升内存,关闭没有降下来,那有可能内存泄露,给你优化渲染提供参考!