UNPKG

atikin-eco-logger

Version:

A sustainable coding metrics tool for measuring energy consumption and runtime efficiency.

35 lines (29 loc) 1.09 kB
const { performance } = require('perf_hooks'); const os = require('os'); /** * Measure runtime and estimate energy impact. * @param {Function} fn - The function to measure. * @returns {Object} Metrics object containing runtime and energy usage estimation. */ function ecoLogger(fn) { const startTime = performance.now(); fn(); const endTime = performance.now(); const runtimeMs = endTime - startTime; const cpuUsage = os.cpus().reduce((acc, cpu) => acc + cpu.times.user + cpu.times.sys, 0); const energyEstimate = (cpuUsage * 0.00005).toFixed(4); // Estimation formula. return { runtime: `${runtimeMs.toFixed(2)} ms`, energyImpact: `${energyEstimate} kWh`, }; } /** * Log metrics to a file. * @param {Object} metrics - Metrics object to log. */ function logMetrics(metrics) { const fs = require('fs'); const log = `Runtime: ${metrics.runtime}, Energy Impact: ${metrics.energyImpact}\n`; fs.appendFileSync('ecoLogger.log', log, 'utf8'); } module.exports = { ecoLogger, logMetrics };