{"id":21417973,"url":"https://github.com/msg-systems/jpowermonitor","last_synced_at":"2025-10-26T14:45:42.276Z","repository":{"id":168160074,"uuid":"611185099","full_name":"msg-systems/jpowermonitor","owner":"msg-systems","description":"JUnit Extension and Java Agent to measure the power consumption of Java applications in watt hours or joule.","archived":false,"fork":false,"pushed_at":"2024-03-25T05:30:56.000Z","size":378,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-03-25T06:37:18.182Z","etag":null,"topics":["agent","cpuusage","greencoding","java","powerconsumption"],"latest_commit_sha":null,"homepage":"https://mvnrepository.com/artifact/io.github.msg-systems/jpowermonitor","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/msg-systems.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-03-08T09:49:53.000Z","updated_at":"2024-04-15T06:48:10.173Z","dependencies_parsed_at":"2023-09-04T08:30:54.210Z","dependency_job_id":"7cdf9aea-8b0f-4e2b-94e3-b54249bf557a","html_url":"https://github.com/msg-systems/jpowermonitor","commit_stats":null,"previous_names":["msg-systems/jpowermonitor"],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msg-systems%2Fjpowermonitor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msg-systems%2Fjpowermonitor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msg-systems%2Fjpowermonitor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msg-systems%2Fjpowermonitor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/msg-systems","download_url":"https://codeload.github.com/msg-systems/jpowermonitor/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225950781,"owners_count":17550322,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent","cpuusage","greencoding","java","powerconsumption"],"created_at":"2024-11-22T19:18:24.196Z","updated_at":"2025-10-17T16:39:56.521Z","avatar_url":"https://github.com/msg-systems.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# jPowerMonitor\nJUnit Extension and Java Agent for energy consumption measurement.\n\n### Description\nThe power consumption of Java applications should become measurable, and thus visible, with the help of jPowerMonitor.\nThis library includes an extension for measuring unit tests, as well as a Java agent for measuring any Java application.\nThe Java agent collects the activity of the application to be measured at regular, configurable intervals. The agent takes into account the power consumption provided by the configured measurement tool.\nThe CPU usage of the program and the current power consumption are aggregated to energy consumption per method over runtime and written into a CSV file.\nThe result of the measurement is the energy consumption in watt-hours or joule.\n\n### Quick Start\n- Install and configure Tool __Libre Hardware Monitor__: https://github.com/LibreHardwareMonitor/LibreHardwareMonitor\n  - Configure Libre Hardware Monitor to start a web server:\n      ![Webserver aktivieren](docs/lhm-webserver.png)\n  - If necessary, an alternative port (default port is 8085) can be also activated there.\n  - __IMPORTANT: To start the web server, Libre Hardware Monitor may have to be started as administrator.__\n  - After that the tool is also accessible in your browser: http://localhost:8085/.\n  - The jPowerMonitor JUnit extension and the Java Agent internally read the json document, which can be retrieved at http://localhost:8085/data.json.\n- The tool __HWiNFO__ or __another tool that writes sensor values to a CSV file__ could be used alternatively, __measurement -\u003e method__ must be set to 'csv' and Logging to CSV in HWiNFO must be active: https://www.hwinfo.com/\n  - Configure HWiNFO to log the values of the power sensors to the CSV file.\n  - Start the logging in HWiNFO to a file e.g. in your project directory.\n- If no measurement tool available or no measurement interfaces accessible (e.g. in virtualized cloud scenarios) configure\n__measurement -\u003e method__ to 'est' (@since jpowermonitor-1.2.0) and configure appropriate 'cpuMinWatts' / 'cpuMaxWatts' according to your platform (@see https://github.com/cloud-carbon-footprint/cloud-carbon-coefficients/tree/main/data).\n- To start the __Java agent__, the \"fat jar\" (incl. dependencies, with name `jpowermonitor-\u003cversion\u003e-all.jar`) must be __downloaded from mvn central [here](https://repo.maven.apache.org/maven2/io/github/msg-systems/jpowermonitor/)__ or __must first be built__ with the Gradle task `shadowJar`.\n- __Copy `src/main/resources/jpowermonitor-template.yaml` to the execution directory and rename it to `./jpowermonitor.yaml`__.\n- __Configure (at least) measurement -\u003e lhm -\u003e paths -\u003e path to match your machine__ for using Libre Hardware Monitor, or __the CSV section__ to use HWiNFO or __another tool that writes sensor values to a CSV file__ or __estimation 'est'__ (@since jpowermonitor:1.2.0).\n- For using the __JUnit Extension__ see below section __[JUnit Tests](#JunitTests)__\n- For more configuration settings see below section __[Configuration](#Configuration)__.\n\n\u003cspan id=\"Configuration\"\u003e\u003cspan\u003e\n### Configuration\nThe configuration is done via a YAML file. Normally this would be `jpowermonitor.yaml`. The agent\nhas multiple ways of getting this configuration:\n1. You can pass it as a programm argument, see section above. If not, it will simply assume the name\n   and path is `jpowermonitor.yaml`.\n2. It first tries to read this path as an external file.\n3. If that fails, it tries to load this path from the JAR's resources\n\nFor the configuration of the JUnit extension a yaml file with the name of the executed test is searched.\n\n| configuration path                                                 | description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | optional  | default value                    |\n|--------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------|----------------------------------|\n| initCycles                                                         | The number of cycles to initialize for measuring the base load on the system.  \u003cbr/\u003e_(Parameter is only used in JUnitExtension, not in JavaAgent)_                                                                                                                                                                                                                                                                                                                                                                                                              | X         | 10                               |\n| samplingIntervalForInitInMs                                        | Polling interval for initialization phase.  \u003cbr/\u003e_(Parameter is only used in JUnitExtension, not in JavaAgent)_                                                                                                                                                                                                                                                                                                                                                                                                                                                 | X         | 1000                             |\n| calmDownIntervalInMs                                               | After initialization, the system waits until the test starts.  \u003cbr/\u003e_(Parameter is only used in JUnitExtension, not in JavaAgent)_                                                                                                                                                                                                                                                                                                                                                                                                                              | X         | 1000                             |\n| percentageOfSamplesAtBeginningToDiscard                            | What percentage of samples should be discarded at the beginning of the measurement to get more meaningful results. Meaningful: 5-20%.  \u003cbr/\u003e_(Parameter is only used in JUnitExtension, not in JavaAgent)_                                                                                                                                                                                                                                                                                                                                                      | X         | 15                               |\n| samplingIntervalInMs                                               | Polling interval for test phase.  \u003cbr/\u003e_(Parameter is only used in JUnitExtension, not in JavaAgent)_                                                                                                                                                                                                                                                                                                                                                                                                                                                           | X         | 300                              |   \n| carbonDioxideEmissionFactor                                        | Conversion factor to calculate approximated CO2 consumption in grams from energy consumption per kWh. Depends on the energy mix of your location, for Germany compare e.g. https://www.umweltbundesamt.de/themen/klima-energie/energieversorgung/strom-waermeversorgung-in-zahlen#Strommix                                                                                                                                                                                                                                                                      | X         | 485                              |\n| measurement -\u003e method                                              | Specify which measurement method to use. Possible values: lhm, csv, est (@since jpowermonitor:1.2.0)                                                                                                                                                                                                                                                                                                                                                                                                                                                            |           | 'lhm'                            |\n| measurement -\u003e csv                                                 | Measure the power using a CSV File Source. The source could be supplied from e.g. HWiNFO (see https://www.hwinfo.com)                                                                                                                                                                                                                                                                                                                                                                                                                                           | X         |                                  |\n| measurement -\u003e csv -\u003e inputFile                                    | Path to csv file to read measure values from                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |           | 'hwinfo.csv'                     |\n| measurement -\u003e csv -\u003e lineToRead                                   | Which line in the csv input file contains the current measured values? The first or the last? This depends on the measurement tool. Possible value: first, last                                                                                                                                                                                                                                                                                                                                                                                                 | X         | 'last'                           |\n| measurement -\u003e csv -\u003e columns                                      | Columns to read, index starts at 0.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |           |                                  |\n| measurement -\u003e csv -\u003e columns -\u003e index                             | Index from a sensor, index starts at 0.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |           | 95                               |\n| measurement -\u003e csv -\u003e columns -\u003e name                              | Name of a sensor                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |           | 'CPU Package Power [W]'          |\n| measurement -\u003e csv -\u003e columns -\u003e energyInIdleMode                  | For the current measuring sensors the base load per sensor path can be configured (self-measured). If nothing is specified, then a base load measurement is performed in `@BeforeAll` (see also initCycles and samplingIntervalForInitInMs) and this value is used.                                                                                                                                                                                                                                                                                             | X         |                                  |\n| measurement -\u003e csv -\u003e encoding                                     | Encoding to use for reading the csv input file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | X         | 'UTF-8'                          |\n| measurement -\u003e csv -\u003e delimiter                                    | Delimiter to use for separating the columns in the csv input file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | X         | ','                              |\n| measurement -\u003e lhm                                                 | Measure the Power using Libre Hardware Monitor (see https://github.com/LibreHardwareMonitor/LibreHardwareMonitor) _Libre Hardware monitor must be started in administrator mode_                                                                                                                                                                                                                                                                                                                                                                                | X         |                                  |\n| measurement -\u003e lhm -\u003e url                                          | Url of the Libre Hardware Monitor incl. port                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |           |                                  |\n| measurement -\u003e lhm -\u003e paths                                        | Multiple paths to the sensors can be specified. This depends on the machine and must be viewed in the Libre Hardware Monitor.                                                                                                                                                                                                                                                                                                                                                                                                                                   |           |                                  |\n| measurement -\u003e lhm -\u003e paths -\u003e path                                | Path to a sensor                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |           |                                  |\n| measurement -\u003e lhm -\u003e paths -\u003e energyInIdleMode                    | For the current measuring sensors the base load per sensor path can be configured (self-measured). If nothing is specified, then a base load measurement is performed in `@BeforeAll` (see also initCycles and samplingIntervalForInitInMs) and this value is used.                                                                                                                                                                                                                                                                                             | X         |                                  |\n| measurement -\u003e est                                                 | Use estimated values according to Etsy's “Cloud Jewels” method (https://www.etsy.com/codeascraft/cloud-jewels-estimating-kwh-in-the-cloud) to estimate energy coefficients (kWh) for cloud service compute, storage, networking, and memory usage. See https://www.cloudcarbonfootprint.org/docs/methodology/#energy-estimate-watt-hours. Find the cloud-platform values here https://github.com/cloud-carbon-footprint/cloud-carbon-coefficients/tree/main/data or here https://github.com/re-cinq/emissions-data/tree/main/data/v2 @since jpowermonitor:1.2.0 |           |                                  |\n| measurement -\u003e est -\u003e cpuMinWatts                                  | Minimum CPU watts (idle).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |           | 0.74 (AWS EC2 avg.)              |\n| measurement -\u003e est -\u003e cpuMaxWatts                                  | Maximum CPU watts (100% load).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |           | 3.5 (AWS EC2 avg.)               |\n| csvRecording -\u003e resultCsv                                          | __Only affects the JUnit extension__: Result CSV Name (specify paths with slash, they will be created automatically)                                                                                                                                                                                                                                                                                                                                                                                                                                            | X         |                                  |\n| csvRecording -\u003e measurementCsv                                     | __Only affects the JUnit extension__: Measurement CSV Name (specify paths with slash, they will be created automatically)                                                                                                                                                                                                                                                                                                                                                                                                                                       | X         |                                  |\n| javaAgentCfg -\u003e packageFilter                                      | Filter power and energy for methods starting with this packageFilter names, write results of filtered methods to separate CSV files.                                                                                                                                                                                                                                                                                                                                                                                                                            | X         | 'group.msg', 'com.msgforbanking' |\n| javaAgentCfg -\u003e measurementIntervalInMs                            | Energy measurement interval in milliseconds for the Java Agent. This is the interval the data source for the sensor values is questioned for new values.                                                                                                                                                                                                                                                                                                                                                                                                        | X         | 1000                             |\n| javaAgentCfg -\u003e gatherStatisticsIntervalInMs                       | Gather statistics interval in milliseconds. This is the interval the stacktrace of each active thread is questioned for active methods. Should be smaller than `measurementIntervalInMs`.                                                                                                                                                                                                                                                                                                                                                                       | X         | 10                               |\n| javaAgentCfg -\u003e writeEnergyMeasurementsToCsvIntervalInS            | Write energy measurement results to CSV files interval in seconds. Leave empty to write energy measurement results only at program exit (be sure your application to measure exits \"gracefully\", thus by calling System.exit(..), else results might be lost!).                                                                                                                                                                                                                                                                                                 | X         | 30                               |\n| javaAgentCfg -\u003e monitoring                                         | Section for configuration of monitoring interfaces.  @since jpowermonitor:1.2.0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |           |                                  |\n| javaAgentCfg -\u003e monitoring -\u003e prometheus                           | Section for configuration of Prometheus monitoring interface.  @since jpowermonitor:1.2.0                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |           |                                  |\n| javaAgentCfg -\u003e monitoring -\u003e prometheus -\u003e enabled                | Set to true, if prometheus monitoring should be enabled. This will start a HttpServer on the configured port.                                                                                                                                                                                                                                                                                                                                                                                                                                                   | X         | false                            |\n| javaAgentCfg -\u003e monitoring -\u003e prometheus -\u003e httpPort               | Prometheus Http Server Port. Prometheus will ask the jPowerMonitored application for metrics on this port.                                                                                                                                                                                                                                                                                                                                                                                                                                                      | X         | 1234                             |\n| javaAgentCfg -\u003e monitoring -\u003e prometheus -\u003e writeEnergyIntervalInS | Write energy measurement results to Prometheus interval in seconds.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | X         | 30                               |\n| javaAgentCfg -\u003e monitoring -\u003e prometheus -\u003e publishJvmMetrics      | Should the default JVM Metric be published to Prometheus? This includes information about GC, memory etc.                                                                                                                                                                                                                                                                                                                                                                                                                                                       | X         | false                            |\n\nIf no base load (`energyInIdleMode`) is specified for a path, this is measured before each test. So a mixed operation between configuration of the base load and measurement is also possible and the results can be compared (some sensors provide very similar values).\nFor non-current measuring sensors (e.g. temperature) the base load is not calculated extra and also not subtracted from the measured value! It is only output if a base load must also be calculated for a current-measuring sensor because this is not specified in the configuration.\n\n### Integration into your own project\n#### Java Agent\n- You may build the jpowermonitor fat jar using the build target `shadowJar` and the copy the `-all.jar` into a folder of your project.\n- You can use this jar for the java agent. Alternatively you may download the fat jar from mvn central [here](https://repo.maven.apache.org/maven2/io/github/msg-systems/jpowermonitor/).\n- For testing call with `java -javaagent:.\\build\\libs\\jpowermonitor-\u003cversion\u003e-all.jar[=path-to-jpowermonitor.yaml] -jar .\\build\\libs\\jpowermonitor-demo-\u003cversion\u003e.jar [runtimeSeconds] [cpuThreads]`\n- The `.\\build\\libs\\jpowermonitor-demo-\u003cversion\u003e.jar` is just an example and can be replaced by any `jar` of your choice\n- The configuration can be passed as a parameter using the `=` sign! If nothing is passed, the default configuration file `jpowermonitor.yaml` is searched.\n- For starting the agent with Spring Boot, Servlet-Container etc. please consult the respective documentation for adding a java agent.\n  - e.g. for use with gradle and Spring Boot you may use\n   ``` \n    bootRun {\n      jvmArgs += [\"-javaagent:./lib/jpowermonitor-1.2.0-all.jar=./lib/jpowermonitor.yaml\"]\n    }\n    ```\n   in your gradle script.\n\n\n\u003cspan id=\"JunitTests\"\u003e\u003cspan\u003e\n#### JUnit Tests\nThe add the test dependency to your gradle build (analogue for maven builds):\n```\n    testImplementation(\n        [group: 'io.github.msg-systems', name: 'jpowermonitor', version: jPowerMonitorVersion],\n    )\n```\n\nThe extension is designed for JUnit 5 (jupiter) tests and is included into your test class as follows:\n```\n@ExtendWith({JPowerMonitorExtension.class})\n```\n\njPowerMonitor then searches for a configuration file with the name of the executed test + `.yaml` extension.\nFor example if your test is named `MyAlgorithmText.java` then the configuration for jPowerMonitor is expected to be found in `MyAlgorithmText.yaml` somewhere in the classpath.\n\nThe tests are best executed as `@RepeatedTests(...)` in order to obtain several measurements. For example always 10 times.\nIn the result CSV (configuration: `resultCsv`) you can then calculate an average of the results in Excel.\n\n`@SensorValues` annotated fields in the test class of the type `List\u003cSensorValue\u003e` can be retrieved after each test in the `@AfterEach` method.\n\nA `SensorValue` contains the resulting measured value with name of the sensor and the following additional information:\n- `Unit unit`: The unit of the value (e.g. W, J, Wh)\n- `BigDecimal powerInIdleMode`: The power consumption that has been measured in idle mode.\n- `LocalDateTime executionTime`: The execution time of measure.\n- `long durationOfTestInNanoSeconds`: The duration of the whole test.\n- `BigDecimal valueWithoutIdlePowerPerHour`: The value without the idle power value.\n- `BigDecimal valueWithIdlePowerPerHour`: The value together with the idle power value.\n\nThe sensor values could be used to create your own output file in your own format.\n\nThe file for the measuring points can be configured under `csvRecording.measurementCsv`. jPowerMonitor outputs all considered measurement points (also those of the base load measurement, if it takes place) into this file.\n\n_Please note_: the first `percentageOfSamplesAtBeginningToDiscard`% measurement points are always discarded.\n\nThe result file can be configured under `csvRecording.resultCsv`. The summary of energy consumption is written to this file.\n\nThe headers of the csv output file are configured in the [csvExport.properties](src/main/resources/csvExport.properties) (default language English).\nThe file currently is translated into German and French and is locale dependent.\nYou may add your own locale and add the translated file to the classpath. You may set the language via JVM option e.g. `-Duser.language=es`.\n\n## Prometheus Integration\n### Information\nFind information about connecting grafana and prometheus e.g. here:\nhttps://prometheus.io/docs/visualization/grafana\n\n### PromQL Queries for jPowerMonitor\n\n##### All jPowerMonitor metrics\n`{__name__=~\"jPowerMonitor_.*\"}`\n\n##### Top 5 power per method filtered metrics\nShow average power per method as multiple threads may execute same method and usually one wants to see the average: \n\n`topk(5, sort_desc(avg by(method) (jPowerMonitor_power_per_method_filtered{job=~\"jPowerMonitor\"})))`\n\n##### Top 5 energy per method filtered metrics\n`topk(5, sort_desc(sum by(method) (jPowerMonitor_energy_per_method_filtered{job=~\"jPowerMonitor\"})))`\n\n##### Top 5 CO2 per method filtered metrics\n`topk(5, sort_desc(sum by(method) (jPowerMonitor_co2_per_method_filtered{job=~\"jPowerMonitor\"})))`\n\n##### Additional attributes\nYou may specify the following additional attributes: \n* pid - get only data for one process id:\n`topk(5, sort_desc(sum by(method) (jPowerMonitor_energy_per_method_filtered{pid=\"27712\", job=~\"jPowerMonitor\"})))`\n* thread - get only data for one thread:\n  `topk(5, sort_desc(sum by(method) (jPowerMonitor_energy_per_method_filtered{thread=\"main\", job=~\"jPowerMonitor\"})))`\n\n\n\n### Limitations\n- If built-in benchmark is run with all available CPU-threads (default) parallel measurement result will be too low since PowerMeasurement-Thread does not get enough time in 100% CPU load scenario -\u003e Try with 2-4 threads less for proper results.\n\n#### Note\nThis markdown can be converted to html with\n`pandoc --self-contained -t slidy -c docs/slidy.css -o Readme.html README.md` to html and from there to pdf via print function of the browser.\n\n# Copyright \u0026 License\nCopyright \u0026copy; 2022-2025 msg for banking ag \u003cbr/\u003e\nLicensed under [Apache License 2.0](./LICENSE.txt)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmsg-systems%2Fjpowermonitor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmsg-systems%2Fjpowermonitor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmsg-systems%2Fjpowermonitor/lists"}