@@ -114,12 +114,25 @@ function prepareBenchmarkProjects(
114114}
115115
116116async function collectSamples ( modulePath : string ) {
117+ let numOfConsequentlyRejectedSamples = 0 ;
117118 const samples = [ ] ;
118119
119120 // If time permits, increase sample size to reduce the margin of error.
120121 const start = Date . now ( ) ;
121122 while ( samples . length < minSamples || ( Date . now ( ) - start ) / 1e3 < maxTime ) {
122123 const sample = await sampleModule ( modulePath ) ;
124+
125+ if ( sample . involuntaryContextSwitches > 0 ) {
126+ numOfConsequentlyRejectedSamples ++ ;
127+ if ( numOfConsequentlyRejectedSamples > 5 ) {
128+ throw Error (
129+ 'Can not sample benchmark due to 5 consequent runs beings rejected because of context switching' ,
130+ ) ;
131+ }
132+ continue ;
133+ }
134+ numOfConsequentlyRejectedSamples = 0 ;
135+
123136 assert ( sample . clocked > 0 ) ;
124137 assert ( sample . memUsed > 0 ) ;
125138 samples . push ( sample ) ;
@@ -356,6 +369,7 @@ interface BenchmarkSample {
356369 name : string ;
357370 clocked : number ;
358371 memUsed : number ;
372+ involuntaryContextSwitches : number ;
359373}
360374
361375function sampleModule ( modulePath : string ) : Promise < BenchmarkSample > {
@@ -377,16 +391,20 @@ function sampleModule(modulePath: string): Promise<BenchmarkSample> {
377391
378392 const memBaseline = process.memoryUsage().heapUsed;
379393
394+ const resourcesStart = process.resourceUsage();
380395 const startTime = process.hrtime.bigint();
381396 for (let i = 0; i < benchmark.count; ++i) {
382397 benchmark.measure();
383398 }
384399 const timeDiff = Number(process.hrtime.bigint() - startTime);
400+ const resourcesEnd = process.resourceUsage();
385401
386402 process.send({
387403 name: benchmark.name,
388404 clocked: timeDiff / benchmark.count,
389405 memUsed: (process.memoryUsage().heapUsed - memBaseline) / benchmark.count,
406+ involuntaryContextSwitches:
407+ resourcesEnd.involuntaryContextSwitches - resourcesStart.involuntaryContextSwitches,
390408 });
391409 ` ;
392410
0 commit comments