@@ -33,8 +33,7 @@ export class PerfMetrics {
3333 }
3434
3535 public get Duration ( ) : number {
36- // TODO check if any of `Duration` fields is maybe a sum of the others. E.g. verify the measured CPU usage manually.
37- return this . _metrics . reduce ( ( sum , metric ) => metric . name . endsWith ( 'Duration' ) ? sum + metric . value : sum , 0 ) ;
36+ return this . _find ( 'TaskDuration' ) ;
3837 }
3938
4039 public get JSHeapUsedSize ( ) : number {
@@ -46,16 +45,17 @@ export class PerfMetricsSampler {
4645 private _consumers : PerfMetricsConsumer [ ] = [ ] ;
4746 private _timer ! : NodeJS . Timer ;
4847
48+ private constructor ( private _cdp : playwright . CDPSession ) { }
49+
4950 public static async create ( cdp : playwright . CDPSession , interval : number ) : Promise < PerfMetricsSampler > {
50- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
51+ const self = new PerfMetricsSampler ( cdp ) ;
5152 await cdp . send ( 'Performance.enable' , { timeDomain : 'timeTicks' } )
5253
53- const self = new PerfMetricsSampler ( ) ;
54+ // collect first sample immediately
55+ void self . _collectSample ( ) ;
5456
55- self . _timer = setInterval ( async ( ) => {
56- const metrics = await cdp . send ( 'Performance.getMetrics' ) . then ( ( v ) => v . metrics ) ;
57- self . _consumers . forEach ( ( cb ) => cb ( new PerfMetrics ( metrics ) ) . catch ( console . log ) ) ;
58- } , interval ) ;
57+ // and set up automatic collection in the given interval
58+ self . _timer = setInterval ( self . _collectSample . bind ( self ) , interval ) ;
5959
6060 return self ;
6161 }
@@ -67,4 +67,10 @@ export class PerfMetricsSampler {
6767 public stop ( ) : void {
6868 clearInterval ( this . _timer ) ;
6969 }
70+
71+ private async _collectSample ( ) : Promise < void > {
72+ const response = await this . _cdp . send ( 'Performance.getMetrics' ) ;
73+ const metrics = new PerfMetrics ( response . metrics ) ;
74+ this . _consumers . forEach ( cb => cb ( metrics ) . catch ( console . error ) ) ;
75+ }
7076}
0 commit comments