Skip to content

Commit

Permalink
support measuring emissions in specific time interval
Browse files Browse the repository at this point in the history
  • Loading branch information
sumn2u committed Nov 26, 2023
1 parent 406ea99 commit 2762164
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ setTimeout(async () => {
| `getEnergyInfo()` | Gives information about the energy grid of the connected network and its composition. |
| `start()` | Starts logging the hardware energy consumption. |
| `end()` | Computes the carbon emission based on the computation power usage and regional carbon intensity. |
| `startMeasurementWithInterval(milliseconds)` | Measures carbon consumption in an interval (milliseconds). |
| `stopPowerMeasurement()` | Clear the timer interval set in `startMeasurementWithInterval()`. |


## Testing
Expand Down
12 changes: 12 additions & 0 deletions examples/timer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import NodeCarbon from '../index.js';

// Create an instance of the NodeCarbon class
const nodeCarbon = new NodeCarbon();

// Measure carbon consumption in an interval (milliseconds)
nodeCarbon.startMeasurementWithInterval(6000); // Measure every minute

// Clear the timer interval after a specific time (e.g., 30 seconds)
setTimeout(async () => {
await nodeCarbon.stopPowerMeasurement();
}, 30000); // Stop after 30 seconds
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-carbon",
"version": "0.0.6",
"version": "0.0.7",
"type": "module",
"description": "calculate carbon footprints of current node process",
"main": "index.js",
Expand Down
49 changes: 49 additions & 0 deletions src/powerConsumptionMeasurement.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class PowerConsumptionMeasurement {
this.geoPowerUsage = 0;
// Store the carbon intensity information
this.carbonIntesityInfo = null;
// Initialize member variables
this.timer = null;
}

/**
Expand All @@ -43,6 +45,44 @@ class PowerConsumptionMeasurement {
// Start measuring memory usage
this.memoryUsageMeasurement.start();
}

/**
* Starts measuring power consumption at regular intervals.
*
* @param {number} intervalDuration The duration of the interval in milliseconds.
*/
async startMeasurementWithInterval(intervalDuration) {
// Validate the interval duration
if (typeof intervalDuration !== 'number' || intervalDuration <= 0) {
throw new Error('Invalid intervalDuration: must be a positive number');
}

// Start measuring power consumption initially
await this.start();

// Set up a timer to stop and report power consumption at regular intervals
this.timer = setInterval(async () => {
// Stop measuring power consumption and report the results
await this.stopAndReport();

// Restart power consumption measurements for the next interval
await this.start();
}, intervalDuration);
}

/**
* Stops measuring power consumption and reports the results.
*/
async stopAndReport() {
// Stop measuring power consumption and gather the results
const powerConsumptionInfo = await this.stop();
// Log the power consumption information to the console
console.log('Power Consumption Report:');
console.log('CPU Usage:', powerConsumptionInfo.cpuUsageInfo);
console.log('Memory Usage:', powerConsumptionInfo.memoryUsageInfo);
console.log('Carbon Emission:', powerConsumptionInfo.carbonEmission);
console.log('Elapsed Time:', powerConsumptionInfo.elapsedTime);
}
/**
* Asynchronously retrieves and stores the carbon intensity information for the current country
*/
Expand Down Expand Up @@ -77,6 +117,15 @@ class PowerConsumptionMeasurement {
}
}

/**
* Stops the ongoing power consumption measurement and cleans up the timer.
*/
stopPowerMeasurement() {
// Clear the timer to prevent further interval-based measurements
clearInterval(this.timer);
this.timer = null;
}

/**
* Stop measuring power consumption and return the results. This includes stopping the CPU
* and memory usage measurements and calculating the total power consumption.
Expand Down
25 changes: 25 additions & 0 deletions test/powerConsumptionMeasurement.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,29 @@ describe('PowerConsumptionMeasurement', () => {
expect(energyUsageInfo.biofuel_electricity).to.equal(mockEnergyInfo.biofuel_electricity);
expect(energyUsageInfo.coal_electricity).to.equal(mockEnergyInfo.coal_electricity);
});

it('should start measuring power consumption and stop at the specified interval', async () => {
// Create an instance of PowerConsumptionMeasurement
const powerConsumptionMeasurement = new PowerConsumptionMeasurement();

// Create a mock function for the stopAndReport method
const stopAndReportStub = sinon.stub().resolves();
powerConsumptionMeasurement.stopAndReport = stopAndReportStub;

// Set a timeout to wait for the interval to complete (adjust as needed)
const waitTime = 1000; // 1 second
const intervalDuration = 600;

// Call the startMeasurementWithInterval method
await powerConsumptionMeasurement.startMeasurementWithInterval(intervalDuration);

// Wait for a sufficient time to allow the interval to execute
await new Promise(resolve => setTimeout(resolve, waitTime));

// Verify that the `stopAndReport` method was called
expect(stopAndReportStub.called).to.be.true

// Call the stopPowerMeasurement method to stop the test explicitly
await powerConsumptionMeasurement.stopPowerMeasurement();
})
});

0 comments on commit 2762164

Please sign in to comment.