aboutsummaryrefslogtreecommitdiff
path: root/demo/src/cpu-performance.ts
blob: a4afc7328a4fdcb533f6ed80b68bdcf05a0e8e79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { CPU } from 'avr8js';

export class CPUPerformance {
  private prevTime = 0;
  private prevCycles = 0;
  private samples = new Float32Array(64);
  private sampleIndex = 0;

  constructor(private cpu: CPU, private MHZ: number) {}

  reset() {
    this.prevTime = 0;
    this.prevCycles = 0;
    this.sampleIndex = 0;
  }

  update() {
    if (this.prevTime) {
      const delta = performance.now() - this.prevTime;
      const deltaCycles = this.cpu.cycles - this.prevCycles;
      const deltaCpuMillis = 1000 * (deltaCycles / this.MHZ);
      const factor = deltaCpuMillis / delta;
      if (!this.sampleIndex) {
        this.samples.fill(factor);
      }
      this.samples[this.sampleIndex++ % this.samples.length] = factor;
    }
    this.prevCycles = this.cpu.cycles;
    this.prevTime = performance.now();
    const avg = this.samples.reduce((x, y) => x + y) / this.samples.length;
    return avg;
  }
}