I'm attempting to time the execution of a simple asynchronous function as it executes within a React Native app. I tried to test this by creating a sample function which resolves a promise after a known amount of time.
However, I do not see execution times matching when the promise should return using setTimeout.
I wrote a simple benchmark test function in Typescript to run a functionUnderTest a given number of times, and record the time elapsed during execution:
export const timeExecution = async (functionUnderTest: () => void | Promise<void>, numberOfExecutions: number) : Promise<number[]> => { let executionTimesMilli: number[] = []; for (let i = 0; i < numberOfExecutions; i++) { console.log("EXECUTING CALL NUMBER: ", i); const startTimeMilli = Date.now(); await functionUnderTest(); const endTimeMilli = Date.now(); const elaspedTimeMilli = endTimeMilli - startTimeMilli; executionTimesMilli.push(elaspedTimeMilli); } return new Promise<number[]>(resolve => { resolve(executionTimesMilli); });};Into this timer function above, I passed a function which resolves a promise after a chosen number of milliseconds:
export async function sampleAsynchronousFunction() : Promise<void> { return new Promise<void>(resolve => { setTimeout(resolve, DEFAULT_WAIT_TIME_MILLI); });}I executed this function in a bare-bones React Native app, and see unexpected results. At delay times (DEFAULT_WAIT_TIME_MILLI) between 0 and 10,000 ms, I consistently see execution taking between 315-335 ms less time than the input delay time. At delay times of less than 300 ms, this appears as almost no delay at all. Chart of expected vs. observed times attached.
Why is this observed execution time consistently faster than the value of DEFAULT_WAIT_TIME_MILLI? I understand that setTimeout may sometimes run slower than expected, but why would it run so consistently faster?






