You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
AdLike2048/assets/script/game/PerfLoadTimer.ts

57 lines
1.5 KiB

import { game, Game } from 'cc';
/**
* 前台活跃时长计时器:切后台暂停累计,用于 PF 加载耗时(排除挂起脏数据)。
*/
export class PerfLoadTimer {
private readonly _wallStart = Date.now();
private _fgStart = 0;
private _fgTotal = 0;
private _listening = false;
static start(): PerfLoadTimer {
const timer = new PerfLoadTimer();
timer._resumeFg();
timer._listening = true;
game.on(Game.EVENT_HIDE, timer._onHide, timer);
game.on(Game.EVENT_SHOW, timer._onShow, timer);
return timer;
}
/** 前台累计毫秒(100ms 粒度取整由 PerfReport 负责) */
foregroundMs(): number {
return this._fgTotal + (this._fgStart > 0 ? Date.now() - this._fgStart : 0);
}
/** 墙钟毫秒(用于判定是否因后台挂起导致失真) */
wallMs(): number {
return Date.now() - this._wallStart;
}
dispose(): void {
if (!this._listening) return;
game.off(Game.EVENT_HIDE, this._onHide, this);
game.off(Game.EVENT_SHOW, this._onShow, this);
this._pauseFg();
this._listening = false;
}
private _onHide(): void {
this._pauseFg();
}
private _onShow(): void {
this._resumeFg();
}
private _pauseFg(): void {
if (this._fgStart <= 0) return;
this._fgTotal += Date.now() - this._fgStart;
this._fgStart = 0;
}
private _resumeFg(): void {
if (this._fgStart > 0) return;
this._fgStart = Date.now();
}
}