Skip to content

Instantly share code, notes, and snippets.

@whchi
Created December 9, 2024 07:58
Show Gist options
  • Select an option

  • Save whchi/07ff6b43a5b2161e338c6828687f08e7 to your computer and use it in GitHub Desktop.

Select an option

Save whchi/07ff6b43a5b2161e338c6828687f08e7 to your computer and use it in GitHub Desktop.
評估某個 function 的 usage
/**
* usage measureResourceUsage(async()=>{}, logger, label)
* @param func
* @param logger
* @param label
* @private
*/
async measureUsage<T>(
func: () => Promise<T>,
logger: Logger,
label: string,
): Promise<T> {
const startTime = process.hrtime();
const startMemory = process.memoryUsage();
const startCpuUsage = process.cpuUsage();
const result = await func();
const endTime = process.hrtime(startTime);
const endMemory = process.memoryUsage();
const endCpuUsage = process.cpuUsage(startCpuUsage);
const timeTaken = endTime[0] + endTime[1] / 1e9;
const memoryUsed = endMemory.heapUsed - startMemory.heapUsed;
const cpuTime = (endCpuUsage.user + endCpuUsage.system) / 1e6;
logger.log(`${label} took ${timeTaken.toFixed(3)} seconds`);
logger.log(`Memory used: ${(memoryUsed / 1024 / 1024).toFixed(2)} MB`);
logger.log(`CPU time: ${cpuTime.toFixed(2)} ms`);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment