Paper deep dive
Static Metrics Are Insufficient: Predicting Java Method Energy Usage with Execution Time
Muhammad Imran, Vincenzo Stoico, Ivano Malavolta
Intelligence
Status: succeeded | Model: Gemma-4-26B-A4B | Prompt: intel-v1 | Confidence: 92%
Last extracted: 7/8/2026, 4:55:03 AM
Summary
This study investigates the feasibility of predicting method-level energy consumption in Java using static source code metrics and execution time. Profiling 2,786 Java methods, the authors extract 33 static features and measure execution time and energy, training 11 regression models. Results indicate that static metrics alone yield near-zero predictive power (R² â 0), but incorporating execution time as a dynamic feature significantly improves accuracy, achieving an R² of up to 0.46. Execution time, internal method calls, and cyclomatic complexity emerge as the strongest predictors, highlighting the dominance of runtime behavior over static structure in energy estimation.
Entities (15)
Relation Signals (10)
Execution time â improvesaccuracyof â Method-level energy prediction
confidence 96% ¡ Incorporating execution time as a lightweight dynamic input significantly improves accuracy, raising R2 to as high as 0.46.
Static source code metrics â yieldpoorpredictiveperformancefor â Energy consumption
confidence 95% ¡ static source code metrics alone yield poor predictive performance, with average R2 values close to zero.
Random Forest â achievesbestperformancewith â R-squared
confidence 94% ¡ RF achieves the best performance with an R 2 of 0.45...
Cyclomatic complexity â isastrongpredictorof â Energy consumption
confidence 93% ¡ Execution time, internal method calls, and cyclomatic complexity consistently emerge as the strongest predictors of energy consumption.
Internal method calls â isastrongpredictorof â Energy consumption
confidence 92% ¡ Execution time, internal method calls, and cyclomatic complexity consistently emerge as the strongest predictors of energy consumption.
srcML â isusedfor â Static analysis
confidence 91% ¡ each Java file was parsed using srcML to apply XPath queries.
async-profiler â isusedfor â Execution time measurement
confidence 90% ¡ For CPU sampling, we used async-profiler to collect method-level execution times...
Cypher Suggestions (0)
No Cypher suggestions yet.
Abstract
Abstract:The increasing energy demand of software systems is raising concerns about their environmental impact and associated costs. Reasoning on energy usage early in the development flow has the potential to significantly reduce the overall energy usage of a software system, as it allows developers to make informed design and refactoring decisions before inefficiencies propagate. However, assessing energy usage without repeated profiling and direct measurement is difficult, which limits early reasoning in practice. This study investigates the limits of method-level energy prediction in Java, examining whether static source code metrics complemented with method-level execution time can estimate the energy consumption of Java methods. We profile 2,786 Java methods to extract 33 static features and measure execution time and energy, then train and compare eleven regression models. Our findings show that static source code metrics alone yield poor predictive performance, with average R2 values close to zero. Incorporating execution time as a lightweight dynamic input significantly improves accuracy, raising R2 to as high as 0.46. Execution time, internal method calls, and cyclomatic complexity consistently emerge as the strongest predictors of energy consumption.
Tags
Links
- Source: https://arxiv.org/abs/2607.06124v1
- Canonical: https://arxiv.org/abs/2607.06124v1
Trouble viewing inline? Open PDF directly â
Full Text
45,631 characters extracted from source content.
Expand or collapse full text
Static Metrics Are Insufficient: Predicting Java Method Energy Usage with Execution Time Muhammad Imran 1 , Vincenzo Stoico 2 , and Ivano Malavolta 2 1 University of LâAquila, LâAquila, Italy muhammad.imran@graduate.univaq.it 2 Vrije Universiteit Amsterdam, Amsterdam, The Netherlands v.stoico@vu.nl, i.malavolta@vu.nl Abstract. The increasing energy demand of software systems is raising concerns about their environmental impact and associated costs. Rea- soning on energy usage early in the development flow has the potential to significantly reduce the overall energy usage of a software system, as it allows developers to make informed design and refactoring decisions before inefficiencies propagate. However, assessing energy usage without repeated profiling and direct measurement is difficult, which limits early reasoning in practice. This study investigates the limits of method-level energy prediction in Java, examining whether static source code metrics complemented with method-level execution time can estimate the energy consumption of Java methods. We profile 2,786 Java methods to extract 33 static features and measure execution time and energy, then train and compare eleven regression models. Our findings show that static source code metrics alone yield poor predictive performance, with averageR 2 values close to zero. Incorporating execution time as a lightweight dy- namic input significantly improves accuracy, raisingR 2 to as high as 0.46. Execution time, internal method calls, and cyclomatic complexity consistently emerge as the strongest predictors of energy consumption. Keywords: Software energy consumption¡ Method-level energy esti- mation¡ Source code metrics¡ Machine learning¡ Java 1 Introduction Energy consumption has emerged as a critical concern in modern software de- velopment, not only in mobile or embedded environments but also in general- purpose computing. As software systems grow increasingly complex and resource- intensive, their energy footprints become non-trivial, impacting battery life, op- erational costs, and environmental sustainability [35]. A significant part of the research in this domain relies on empirical mea- surements, as energy is strongly influenced by the execution environment of the application [10]. These measurements are obtained through repeated executions in controlled environments, often using specialized profiling tools and hardware instrumentation [43]. Although these methods provide precise and reliable en- ergy consumption data, they often require manual setup or hardware access to capture fine-grained data, which limits their routine use in development work- flows [18]. Consequently, during refactoring or design, developers typically lack arXiv:2607.06124v1 [cs.SE] 7 Jul 2026 2Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta accessible ways to reason about energy consumption without repeated profil- ing [39]. The limitations of measurement-based approaches become especially clear when energy profiling is required at fine-grained levels, such as individual methods. Recent studies demonstrate that even small syntactic code changes can introduce measurable variations in energy usage, especially in compiled or performance-sensitive programs [38]. Despite this growing recognition, few studies have systematically modeled energy consumption from static code features like cyclomatic complexity, loop depth, or library usage, especially at the method level. Multiple studies [20, 3] show static features influence energy by shaping control flow, computational in- tensity, and resource access, highlighting their importance in energy modeling. Most work focuses on coarse-grained estimation (language- or library-level) or hybrid methods requiring execution [38, 3]. This gap is particularly notable in Java, where low-level decisions such as collection types and loop constructs af- fect energy in subtle ways [38, 31], while higher-level design patterns have been found largely energy-neutral [37]. These observations motivate approaches that support fine-grained energy awareness while reducing reliance on repeated profil- ing and specialized instrumentation, since energy consumption depends not only on source code but also on its interaction with hardware and runtime character- istics [41], suggesting that combining static and dynamic features may improve prediction accuracy, and at method level, such predictions can directly guide developers toward the specific code units responsible for high energy usage, en- abling targeted optimization. The goal of this study is to assess the extent to which static features ex- tracted from Java methods can explain method-level energy consumption, and to identify their limitations. We further investigate whether adding execution time improves predictive performance. Our research methodology involves pro- filing 2,786 Java methods from 768 files representing 815 programming tasks to collect static features, execution time, and energy measurements. We extract 33 source-level features per method, profile execution time and energy on a fixed testbed, and train eleven regression models through a structured process includ- ing feature selection, model comparison, and hyperparameter tuning. Our findings show that static code features alone yield near-zero predictive power (R 2 â 0), and that only the inclusion of execution time as a lightweight dynamic input raises R 2 to 0.46, indicating that method-level energy is domi- nated by runtime behavior rather than source structure alone. We provide a publicly available replication package [25], containing the dataset, energy measurements, execution times, static features, training scripts, and com- plete experimental results. 2 Related Work Energy Efficiency Recent studies have explored energy efficiency in high- level languages, showing that alternative compilers such as Codon [45], Pythran, and PyPy consistently outperform CPython in execution time and energy effi- ciency [4], and that HOPE [1] and Codon demonstrate similar gains on numerical Static Metrics Are Insufficient: Predicting Java Method Energy3 benchmarks against C++. While these studies show energy gains through com- piler optimization, they focus on coarse-grained program behavior and specific benchmark types or parallel computing use cases. Recent work has also examined fine-grained energy variations caused by structural differences in source code. Stoico et al. [46] demonstrated that small syntactic modifications in Python programs, such as altering list comprehen- sions or loop constructs, can significantly affect both execution time and energy consumption, depending on how the code is compiled and optimized. Similarly, Cursaru et al. [15] showed that functionally equivalent code generated by differ- ent LLM prompts can result in measurable differences in energy usage, driven solely by structural variations. These studies emphasize that source code organi- zation itself can directly influence energy behavior, even though their results are not directly transferable to Java, and motivate the broader question of whether structural source code properties are informative for energy estimation at finer levels of granularity. We investigate this question at the level of individual Java methods using static code features and execution time. Static Code Metrics Several studies have explored static code metrics as pre- dictors of software energy consumption. Kumar et al. [31] showed that Java con- structs such as loops, data types, and collections can significantly impact energy usage. Hamza Alvi et al. [3] proposed the MLEE framework, which applies ma- chine learning for method-level energy estimation in Android applications using structural code features under controlled execution scenarios, though its strong predictive performance relies on platform-specific assumptions not directly trans- ferable to general-purpose Java workloads. Akinli [2] further demonstrated the viability of combining code metrics with learning models for energy prediction across benchmarks. Broader perspectives are offered by Kruglov et al. [30], who emphasize the integration of sustainability metrics into software processes, and Schuler et al. [43], who identify the lack of fine-grained static code-based energy models in the current literature. Beyond energy estimation, static metrics have also proven valuable in predicting security vulnerabilities [17], estimating main- tenance effort [12], and understanding the energy impact of design decisions such as code smells and refactoring [42]. Closest to our work, Goyal et al. [19] recently proposed EnCoDe, which predicts block-level energy of Python code purely from static AST features (R 2 of 0.75), with ground-truth labels obtained via ampli- fied executions of isolated code blocks with fixed inputs. Notably, their ablation shows that complexity metrics alone yield an R 2 of 0.067. In contrast, our study examines a broader set of static features including metrics from software perfor- mance evaluation, adds execution time as a dynamic feature, targets methods executed within complete Java programs rather than isolated code fragments, and performs a structured comparison of multiple regression models with system- atic feature selection and hyperparameter tuning, offering a complete evaluation of ML-based energy estimation at the method level. Machine Learning Models for Prediction While MLEE [3] and Akinli [2] demonstrated the feasibility of ML-based energy estimation at method level, nei- 4Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta (a) Main steps of the study.(b) Profiling using Experiment Runner. Fig. 1: Overview of the study workflow and profiling setup. ther performed extensive model comparison, tuning, or feature selection analysis. Kruglov et al. [30] and Schuler et al. [43] also note the growing trend of model- based estimation, yet few studies systematically compare the performance of different models or assess the impact of tuning and feature selection on predic- tion accuracy. Our study addresses this gap through a structured comparison of eleven regression models evaluated across multiple feature selection and tuning configurations. 3 Study Design We define three research questions (RQs) guiding our investigation: ⡠RQ 1 : To what extent can method-level energy consumption be predicted from static source code features, and how does predictive performance change when execution time is added? This research question assesses the baseline predictive value of static code features and evaluates the marginal effect of adding execution time as a lightweight dynamic input. Models are trained with default hyperparameters. ⡠RQ 2 : What is the effect of feature selection on the performance of energy prediction models? We investigate whether removing less informative features improves generalization and which code characteristics are most predictive of energy usage, offering guidance for developers when dynamic profiling is un- available. ⡠RQ 3 : How does hyperparameter tuning influence model performance for predicting method-level energy usage? We explore whether fine-tuning yields meaningful accuracy gains over defaults, clarifying the relative importance of model optimization versus feature engineering in our prediction setting. Static Metrics Are Insufficient: Predicting Java Method Energy5 Our study follows a structured process consisting of three main steps: (i) subject selection, (i) data preparation, and (i) model training and tuning, as shown in Figure 1(a). 3.1 Subject Selection We selected Java implementations from two publicly available repositories: the Computer Language Benchmarks Game (CLBG) 3 and Rosetta Code 4 . They pro- vide community-contributed implementations of algorithmic tasks across multi- ple languages, typically self-contained and computationally intensive, making them well suited for controlled energy profiling at method level. For Rosetta Code, we used a curated GitHub snapshot 5 organizing 1,228 tasks, of which 1,146 had Java implementations, resulting in 1,790 files across all variants. From CLBG, crawling 10 tasks provided 49 files. We filtered out implementations that: (i) lacked a main method, (i) required user input or a graphical interface, (i) contained infinite loops, (iv) had dupli- cate class names, or (v) could not be compiled due to external dependencies. After filtering 853 Java files corresponding to 812 distinct tasks were retained. 3.2 Data Preparation Data was collected at method level through two complementary pipelines: static analysis for code features and dynamic profiling for execution time and energy. Static Analysis Following established practices in performance analysis [23], each Java file was parsed using srcML [13] to apply XPath queries. We extracted 33 static features per method covering control flow, complexity, and standard library usage, as summarized in Table 1. Features were guided by prior work on software performance [24] and selected by correlating known static metrics with energy to filter out less informative ones, yielding features for 2,786 methods across the 853 files. Dynamic Profiling To collect execution time and energy consumption data, we followed established guidelines for energy measurement [21, 34] and used Ex- periment Runner [27] as experiment orchestrator shown in Figure 1(b). For CPU sampling, we used async-profiler 6 to collect method-level execution times, and for energy measurement, we employed JoularJX 7 , which provides method-level energy estimation within the JVM. The 853 Java files were compiled using javac version 18.0.1.1, producing 1,100 .class files. Profiling commands attach both agents to the JVM via a custom wrapper class, LoopRunner, which executes each programâs main method mul- tiple times in a loop. Since both async-profiler and JoularJX rely on sampling, 3 https://benchmarksgame-team.pages.debian.net/benchmarksgame/index.html 4 https://rosettacode.org/wiki/Rosetta_Code 5 https://github.com/acmeism/RosettaCodeData 6 https://github.com/async-profiler/async-profiler 7 https://w.noureddine.org/research/joular/joularjx 6Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta Table 1: Collected source code features. Level/ CategoryFeature NameDescription (i)meta info method #methodLOCLines of code of the method #nameLenmethod name length methodScopeaccess specifier of the method isOverloadedif the method is overloaded (i) language feature control flow and data #ifno. of if conditions #switchno. of switch statements #caseno. of case statements #forno. of for loops #whileno. of while loops #dono. of doWhile loops #nestedLoopsno. of nested loops (arbitrary depth) #methodCallsno. of methods called #internalCallsno. of internal methods called #externalCallsno. of external methods called #returnno. of return statements #throwno. of throw statements #catchno. of catch statements #cyclocyclomatic complexity #varsno. of the variables declared (i) standard Java APIs utilityjava.utilUtility classes in Java. os and concurrency java.langCore Java classes & Multithreading java.lang.managementManagement interfaces for Java. java.util.concurrentAdvanced concurrency utilities. io java.ioData streams based I/O. java.nioNew I/O for scalable I/O operations. java.nio.channelsChannels for non blocking I/O. java.nio.fileNIO based File I/O enhancements. java.nio.charsetClasses for encoding and decoding. java.netNetworking and communication. javax.net.sslFor secure network communication. strings java.util.regexRegex for pattern matching & Strings. java.textText parsing and formatting classes. mathjava.mathMathematical utilities. repeating executions increases the likelihood of capturing short-lived methods that may not be observed in a single run. We set the repetition count to 20, which captured energy measurements for âź48% more methods and execution- time data for âź14% more methods compared to a single run. Input values for CLBG tasks were taken from the task pages and Rosetta Code inputs were embedded in the implementations. We selected JoularJX as the energy profiler because it provides method-level energy measurements directly within the JVM through agent-based instrumen- tation, correlating runtime method execution with CPU utilization and power readings to attribute total JVM energy consumption to individual methods [36]. Other approaches, including hardware counters such as Intelâs RAPL [28] and tools such as CodeCarbon [33], PowerAPI [16], and RJoules [11], produce sys- tem or process level estimates rather than method-level attribution. JoularJX instead remains lightweight, cross-platform, and compatible with async-profiler for synchronized CPU and energy traces. Prior to profiling, a warm-up phase (re- peated Fibonacci execution) stabilized JVM state (JIT activation and thermal steady state). Each profiling iteration was triggered via HTTP POST to a Flask server on the testbed, followed by a 30-second cool-down period as a standard Static Metrics Are Insufficient: Predicting Java Method Energy7 practice 8 for preventing heat accumulation across sequential runs. Both profil- ers were configured at a 1 ms sampling interval to match JoularJXâs minimum resolution 9 . Profiler outputs (.collapsed for async-profiler, .csv for JoularJX ) were parsed to extract method-level metrics. Execution times were recovered for 1,980 meth- ods and energy values for 1,103 methods. Since async-profiler samples via CPU events while JoularJX operates at fixed temporal intervals [9], profiler coverage is only partially overlapping, reducing the number of methods with complete fea- ture pairs without affecting measurement validity. To mitigate bias, we retained only the intersection of methods reported by both profilers for model training. 3.3 Model Training and Tuning Our approach was inspired by previous studies on software performance [24, 32] and energy estimation [2], using regression models to predict energy from source code characteristics. Table 2 lists the eleven regression models selected based on: (i) prior use in software engineering analytics [24, 32, 2], (i) flexibility to capture linear and non-linear relationships, and (i) availability in scikit-learn 10 for reproducibility. The process follows three steps aligned with RQ1âRQ3: base model training, feature selection, and hyperparameter tuning. Table 2: ML models used in this study. ModelAcronymAlgorithm Random ForestRFEnsemble Gradient BoostingGBEnsemble-Boosting ADA BoostingADAEnsemble-Boosting Hist Gradient BoostingHGBEnsemble-Boosting Lasso RegressionLasso-RLinear k-Nearest NeighborkNNInstance-based Ridge RegressionRidge-RLinear Support Vector MachineSVMKernel-based Linear RegressionLRLinear Multi-Layer PerceptronMLPNeural Network Decision TreeDTDecision Tree Data Pre-processing From the initial 2,786 methods, matching with profiler out- puts (JoularJX and async-profiler) resulted in 902 methods with complete static and dynamic data. After removing methods with zero energy consumption which are likely trivial code paths that would distort training, we got 265 methods re- maining. To deal with the long-tailed distributions of both energy and execution time values, we applied a natural logarithmic transformation, which mitigated skewness and made the variables more suitable for regression modeling. The cat- egorical methodScope feature was one-hot encoded to produce a fully numeric feature matrix. 8 https://luiscruz.github.io/2021/10/10/scientific-guide.html 9 github.com/joular/joularjx/blob/develop/config.properties 10 https://scikit-learn.org/ 8Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta Model Training We define a supervised learning task where each instance cor- responds to a Java method characterized by static features (e.g., lines of code, number of loops), and the target variable is the dynamic energy measure ob- tained through our profiling setup. The training set includes static features and execution time in milliseconds as predictors and energy consumption (measured in Joules) as the target variable. We apply 5-fold cross-validation (rather than 10-fold, to ensure sufficiently large validation samples given our dataset size of 265 methods) to reduce variance due to sampling, using an 80/20 split repeated five times across shuffled partitions. Models are trained with default hyperparam- eters without feature pre-processing, as this initial step establishes the baseline performance evaluated in RQ1. Feature Selection and Configuration Comparison To address RQ2, we applied seven feature pre-processing techniques: RFECV [22], AutoSpearman [26], Selec- tKBest [40] (k â 10, 20, 30), and VarianceThreshold [44]. RFECV eliminates features iteratively based on model feedback; AutoSpearman removes multi- collinear features by thresholding pairwise Spearman correlation. Evaluating all model Ă feature-selection combinations yields 77 configurations (11 models Ă 7 variants). Configurations are compared using R 2 and the five top-performing configurations are carried forward for hyperparameter tuning. Hyperparameter Tuning To address RQ3, we applied RandomizedSearchCV to the top five configurations using model-specific parameter grids available in the replication package [25]. Random search is more efficient than grid or manual search for finding optimal hyperparameters [7]. The tuning objective is to max- imize R 2 . Performance Evaluation We adopt four standard regression metrics, widely used in software effort estimation [6], defect prediction [5], and energy-aware analyt- ics [2, 30, 3]. We use R 2 as the primary indicator of overall performance and for selecting the best model configurations, as it captures how effectively the features explain variance in energy usage. Mean Absolute Error (MAE), Mean Squared Error (MSE), and Mean Absolute Percentage Error (MAPE) complement this by characterizing the magnitude and scale of prediction errors. 4 Results 4.1 RQ 1 : Predictive performance for energy Figure 2 summarizes the baseline results, showing that the predictive perfor- mance of all regression models trained on static features and execution time remains limited. RF achieves the best performance with an R 2 of 0.45, an MSE of 7.15, an MAE of 2.02, and a MAPE of 1.75, offering strong interpretability through its feature importance estimates. At the other extreme, DT performs worst with an R 2 of only 0.05 and a MAPE exceeding 2.8, indicating overfitting and poor generalization. Overall, all models only partially explain the variabil- ity in energy consumption: the best R 2 remains below 0.5, MSE ranges from 7 to 12, and MAPE stays mostly below 2%, indicating that predictions are proportionally close to actual values even when absolute errors are larger. Static Metrics Are Insufficient: Predicting Java Method Energy9 RF GB ADA HGB LassoR kNN RidgeR SVM LR MLP DT 0.0 0.1 0.2 0.3 0.4 R-squared RF GB ADA HGB LassoR kNN RidgeR SVM LR MLP DT 0 2 4 6 8 10 12 MSE RF GB ADA HGB LassoR kNN RidgeR SVM LR MLP DT 0.0 0.5 1.0 1.5 2.0 2.5 MAE RF GB ADA HGB LassoR kNN RidgeR SVM LR MLP DT 0.0 0.5 1.0 1.5 2.0 2.5 MAPE Fig. 2: Baseline prediction performance. 4.2 RQ 2 : Feature selection We evaluated six feature preprocessing techniques against the baseline using all features. Figure 3 reports the R 2 values for all 77 configurations, covering 11 models and seven feature settings. The results show that performance varies across both models and preprocessing techniques, although the gains over the baseline are generally small. Table 3 reports the five best configurations. RF is the most consistent model, appearing in four of the top five configurations. The best result is obtained with Variance Threshold (t6), with an R 2 of 0.463, followed closely by AutoSpearman (0.460), SelectKBest with k = 30 (0.459), and the full feature set (0.454). The only non RF configuration in the top five is AdaBoost with Variance Threshold, reaching an R 2 of 0.453. Table 3: Top 5 configurations based onR 2 score without hyperparameter tuning Model Feature Selector Features Selected MSEMAEMAPER 2 RFVariance Threshold247.0382.0081.6930.463 RFAutoSpearman227.0581.9981.8730.460 RFSelectKBest307.1022.0151.7420.459 RFNone357.1522.0241.7450.454 ADAVariance Threshold247.2182.1622.1520.453 Figure 4(a) shows the SHAP values for the best configuration. log_execution_time is the most influential feature, followed by #internalCalls and other structural features related to control flow and method behavior. Figure 4(b) shows how often each feature was selected. Features such as #catch, #do, #cyclo, and log_execution_time are selected by multiple techniques, while features such as usesJavaUtilConcurrent and usesJavaLangManagement appear less consistently, suggesting that a core subset of structural features contributes more reliably to energy estimation. One non-obvious feature among the top ranks is nameLen: 10Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta t0t1t2t3t4t5t6 0.0 0.1 0.2 0.3 0.4 R-Squared RF t0t1t2t3t4t5t6 GB t0t1t2t3t4t5t6 ADA t0t1t2t3t4t5t6 0.0 0.1 0.2 0.3 0.4 R-Squared HGB t0t1t2t3t4t5t6 LassoR t0t1t2t3t4t5t6 kNN t0t1t2t3t4t5t6 0.0 0.1 0.2 0.3 0.4 R-Squared RidgeR t0t1t2t3t4t5t6 SVM t0t1t2t3t4t5t6 LR t0t1t2t3t4t5t6 0.0 0.1 0.2 0.3 0.4 R-Squared MLP t0t1t2t3t4t5t6 -0.30-0.03-0.09 DT Feature Selection Techniques t0: All_features t1: autospearman t2: kbest_10 t3: kbest_20 t4: kbest_30 t5: rfecv t6: variance threshold >0.01 Fig. 3: Feature-selection performance. although method name length does not directly represent computation, it may act as a weak proxy for design or implementation style. Finally, we isolated the contribution of execution time by training the models without it. Figure 5 compares the R 2 values with and without execution time. Removing execution time causes a substantial performance drop across all mod- els. For RF, R 2 decreases from 0.454 to 0.005 while MAPE increases from 1.75 to 2.27, confirming that execution time is a key lightweight dynamic proxy for predicting energy consumption at the method level. (a) SHAP values for RF with 24 features selected by Variance Threshold (t6). Set 1Set 2Set 3Set 4Set 5 Sets of Features 0 1 2 3 4 5 Selected by (# Techniques) Set 1 (selected by 5 technique(s)): #catch, #do, #if, #switch, #while, cyclo, log_execution_time, methodScope_private, usesJavaMath Set 2 (selected by 4 technique(s)): #internalCalls, #nestedLoops, #return, #throw, #vars, methodScope_public, nameLen, usesJavaIo, usesJavaLang, usesJavaUtilConcurrent Set 3 (selected by 3 technique(s)): #externalCalls, #for, methodLoc, usesJavaText, usesJavaUtil Set 4 (selected by 2 technique(s)): #methodCalls, usesJavaNet Set 5 (selected by 1 technique(s)): execution_time, methodScope_protected, usesJavaLangManagement, usesJavaNioCharset, usesJavaUtilRegex, usesJavaxNetSsl (b) Frequency of features selected by different techniques. Fig. 4: Feature importance analysis for RQ 2 Static Metrics Are Insufficient: Predicting Java Method Energy11 RF GB ADA HGB LassoR kNN RidgeR SVM LR MLP 0.1 0.0 0.1 0.2 0.3 0.4 R-squared without Execution Time with Execution Time Fig. 5: Effect of excluding execution time. 4.3 RQ 3 : Hyperparameter tuning We tuned RF and ADA as they are the only two models featured in the top five configurations in Table 3. Each tuned configuration retained its original feature preprocessing strategy and was evaluated using 5-fold cross-validation. Table 4 reports the results after applying hyperparameter tuning to the five best configurations identified in RQ 2 . For RF, three of the four configurations showed minor gains in R 2 , with MAE and MAPE changing negligibly. AdaBoost slightly degraded after tuning, with R 2 dropping from 0.453 to 0.436 and MSE increasing from 7.218 to 7.413. MAPE improved marginally (2.152 to 2.026) but did not outweigh the overall decline. Overall, these marginal changes sug- gest that ensemble methods such as RF and ADA already perform reasonably well with default hyperparameters on small datasets, and that improving input representations is more impactful than model fine-tuning in this setting. Table 4: Top 5 configurations based onR 2 score with hyperparameter tuning Model Feature Selector Features Selected MSEMAEMAPER 2 RFVariance Threshold247.0712.0602.0710.462 RFNone357.0722.0602.0700.462 RFSelectKBest307.0742.0602.0720.462 RFAutoSpearman227.0872.0642.0410.460 ADAVariance Threshold247.4132.1782.0260.436 To further illustrate the generalization performance of the top-performing model, Figure 6 presents box plots comparing actual and predicted energy values on a logarithmic scale across the five cross-validation folds. Although fold-level R 2 scores range from 0.224 to 0.567, the overall trend shows that predictions approximate the central tendency of the true distribution, with occasional devi- ation in the tails. Most folds maintain MAPE below 2%, except for fold 4, which exhibits greater spread. 12Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta Fig. 6: Box plots comparing actual and predicted log-transformed energy consumption values across all five folds for the top-performing RF configuration. 5 Discussion Our findings show that method-level energy consumption in Java can be partially predicted by combining static code features with execution time, though predic- tive performance remains modest with the best R 2 below 0.47. RF emerged as the most consistent model, while simpler models such as DT and LR under- performed significantly, underscoring the inherent difficulty of energy estimation at fine granularity. Despite these limitations, our results help characterize how static code features relate to method-level energy consumption, providing a basis to identify energy trends rather than exact values. Feature selection techniques provided only slight improvements in predictive performance, but their main value lies in identifying structural code properties that correlate with energy usage, such as control flow, API usage, and method complexity. Execution time stood out as the most predictive feature across all configurations. Importantly, execution time is not included to reduce energy prediction to runtime estimation, but to quantify how much explanatory power static code features retain once runtime effects are taken into account. Prior work has shown that execution time can act as a proxy for energy consumption in mobile environments [14]. Our results empirically confirm this dominance at the method level for general-purpose Java workloads, demonstrating its significance in a domain and granularity where its impact was previously under-explored. Our results complement those of Goyal et al. [19], where static features alone predict Python block-level energy with an R 2 of 0.75: there, each block is mea- sured in isolation through amplified execution under fixed inputs to obtain a sta- ble energy reading. The label therefore reflects the blockâs own computational cost rather than runtime context. Our labels instead capture method energy attributed during full-program execution, where inputs, invocation counts, and JVM runtime mechanisms dominate and are only partially captured by execution time. Hyperparameter tuning, by contrast, delivered minimal gains, suggesting that thoughtful feature selection and preprocessing have greater impact than extensive model optimization in this setting. Static Metrics Are Insufficient: Predicting Java Method Energy13 Static features such as internal method calls and cyclomatic complexity con- sistently emerge as informative predictors, motivating further investigation into novel static feature based energy models and guiding developers toward refac- toring efforts focused on energy optimization. Feature engineering and the in- corporation of additional dynamic features such as CPU usage, which is known to significantly influence power consumption [29] represent the most promising directions for improving prediction accuracy and constitute a natural extension of this work. 5.1 Threats to Validity External validity. The dataset includes 2,786 methods from 768 Java files, mainly drawn from Rosetta Code and CLBG benchmark tasks. These programs are benchmark-style, self-contained, and primarily algorithmic, and therefore do not fully represent large, event-driven, I/O-intensive, or framework-based soft- ware systems. The results are specific to Java programs running on our tested JVM and hardware, mainly reflecting CPU activity, and should not be directly extended to other languages, virtual machines, or architectures such as ARM servers and mobile devices. Results may further vary across JVM vendors and versions, as runtime behavior and energy attribution can differ between imple- mentations. Internal validity. Several factors such as just-in-time compilation, garbage col- lection, and operating-system scheduling can affect both time and energy mea- surements. To minimize their effect, all experiments were conducted on a dedi- cated testbed with fixed CPU frequency, disabled hyper-threading, and minimal background activity, following best practices from prior studies. Each run in- cluded warm-up and cool-down phases to reduce thermal-related measurement variation, and energy readings were averaged over repeated executions. Since multi-threaded Java implementations are not present in CLBG and Rosetta Code, all benchmarks are single-threaded, and the results therefore characterize single-threaded execution behavior only. Furthermore, filtering out incomplete and zero-energy measurements reduced our training dataset to just 265 methods, which represents a thin basis for training and comparing eleven models, limiting the reliability of the model comparison results. Construct validity. The study models method-level energy consumption us- ing JoularJX and async-profiler. JoularJX measures power through RAPL-based domains, which cover only CPU and DRAM and omit peripheral components such as I/O, meaning methods dominated by such activity may appear as zero- energy. Its precision is further affected by hardware counter granularity, sam- pling interval configuration, method call frequency, and the attribution strategy used to map energy readings to individual methods. Prior work has shown that short-lived or infrequently executed methods may produce noisy or unreliable estimates [36, 9], and recent evaluations indicate that sampling at around 1 ms increases profiling overhead and occasionally yields missing or zero readings, whereas longer intervals of approximately 10 ms provide a better tradeoff be- tween accuracy and overhead [8]. Methods reporting zero energy were excluded from analysis. Moreover, method inputs were fixed rather than systematically 14Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta varied, and code coverage was not measured during profiling, which may intro- duce a mismatch between static predictors and the code paths actually exercised. These factors can introduce variance or systematic error into the measured val- ues, potentially influencing model training and evaluation. Conclusion validity. Our use of standard metrics (i.e., MAE, MSE, MAPE, and R 2 ) may not capture all aspects of predictive performance, such as sensi- tivity to outliers. Given the exploratory nature of this study, we do not report statistical significance testing. To mitigate these threats, we rely on multiple complementary metrics and consistent evaluation procedures across all models and configurations. 6 Conclusion and future work This study investigated the limits of method-level energy prediction in Java by profiling 2,786 Java methods to extract 33 static features alongside execution time, and training eleven regression models to assess their predictive power. The results show that static code metrics alone yield poor predictive performance, with R 2 values near zero. Adding execution time as a lightweight dynamic feature significantly improves accuracy, reaching an R 2 of 0.46. Execution time, inter- nal method calls, and cyclomatic complexity consistently emerge as the most influential predictors of energy consumption. Future work could explore larger datasets, extending beyond isolated algo- rithmic tasks to real-world applications that utilize external frameworks. Such projects introduce new layers of abstraction and I/O operations. Evaluating these systems will require understanding how method-level energy profiles in- teract to impact a systemâs overall energy footprint. Additionally, incorporating dynamic features like CPU/GPU and memory usage could further enhance the predictive power of the models. Finally, the reusability of trained models across evolving codebases and hardware, and the energy cost of retraining them, remain open questions for future investigation. References 1. Akeret, J., Gamper, L., Amara, A., Refregier, A.: Hope: A python just-in-time com- piler for astrophysical computations. Astronomy and Computing 10, 1â8 (2015) 2. Akinli Koçak, S.: Software energy consumption prediction using software code met- rics. Ph.D. thesis, Toronto Metropolitan University (2018) 3. Alvi, H.M., Majeed, H., Mujtaba, H., Beg, M.O.: Mlee: Method level energy es- timationâa machine learning approach. Sustainable Computing: Informatics and Systems 32, 100594 (2021) 4. Augier, P., Bolz-Tereick, C.F., Guelton, S., Mohanan, A.V.: Reducing the ecological impact of computing through education and python compilers. Nature Astronomy 5(4) (2021) 5. Baskeles, B., Turhan, B., Bener, A.: Software effort estimation using machine learn- ing methods. In: 22nd international symposium on computer and information sci- ences. IEEE (2007) 6. Bener, A., Misirli, A.T., Caglayan, B., Kocaguneli, E., Calikli, G.: Lessons learned from software analytics in practice. In: The art and science of analyzing software data, p. 453â489. Elsevier (2015) Static Metrics Are Insufficient: Predicting Java Method Energy15 7. Bergstra, J., Bengio, Y.: Random search for hyper-parameter optimization. Journal of machine learning research 13(2) (2012) 8. Brunnert, A.: Evaluating the accuracy of software energy consumption models for java applications at process and transaction levels. In: Proceedings of the 33rd ACM International Conference on the Foundations of Software Engineering (2025) 9. Burchell, H., Larose, O., Kaleba, S., Marr, S.: Donât trust your profiler: An empiri- cal study on the precision and accuracy of java profilers. In: Proceedings of the 20th ACM SIGPLAN International Conference on Managed Programming Languages and Runtimes. p. 100â113 (2023) 10. Castor, F.: Estimating the energy footprint of software systems: a primer. arXiv preprint arXiv:2407.11611 (2024) 11. Chattaraj, R., Chimalakonda, S.: Rjoules: An energy measurement tool for r. In: 38th International Conference on Automated Software Engineering (ASE) (2023) 12. Chowdhury, S., Holmes, R., Zaidman, A., Kazman, R.: Revisiting the debate: Are code metrics useful for measuring maintenance effort? Empirical Software Engi- neering 27(6), 158 (2022) 13. Collard, M.L., Decker, M.J., Maletic, J.I.: Lightweight transformation and fact extraction with the srcml toolkit. In: SCAM 2011 (2011) 14. Corral, L., Georgiev, A.B., Sillitti, A., Succi, G.: Can execution time describe accurately the energy consumption of mobile apps? an experiment in android. In: Proceedings of the 3rd GREENS. p. 31â37 (2014) 15. Cursaru, V.A., Duits, L., Milligan, J., Ural, D., Sanchez, B.R., Stoico, V., Mala- volta, I.: A controlled experiment on the energy efficiency of the source code gen- erated by code llama. In: QUATIC. Springer (2024) 16. Fieni, G., Acero, D.R., Rust, P., Rouvoy, R.: Powerapi: A python framework for building software-defined power meters. Journal of Open Source Software (2024) 17. Ganesh, S., Palma, F., Olsson, T.: Are source code metrics âgood enoughâ in pre- dicting security vulnerabilities? Data 7(9), 127 (2022) 18. Georgiou, S., Rizou, S., Spinellis, D.: Software development lifecycle for energy efficiency: techniques and tools. ACM Computing Surveys (CSUR) 52(4) (2019) 19. Goyal, S., Matathammal, A., Vaidhyanathan, K.: Encode: Energy estimation of source code at design-time. arXiv preprint arXiv:2605.00504 (2026) 20. Grech, N., Georgiou, K., Pallister, J., Kerrison, S., Morse, J., Eder, K.: Static analysis of energy consumption for llvm ir programs. In: Proceedings of the 18th International Workshop on Software and Compilers for Embedded Systems (2015) 21. Guldner, A., Bender, R., Calero, C., et al.: Development and evaluation of a refer- ence measurement model for assessing the resource and energy efficiency of software products and components: Green software measurement model (gsmm). Future Generation Computer Systems 155, 402â418 (2024) 22. Guyon, I., Weston, J., Barnhill, S., Vapnik, V.: Gene selection for cancer classifi- cation using support vector machines. Machine learning 46(1), 389â422 (2002) 23. Imran, M., Cortellessa, V., Di Ruscio, D., Rubei, R., Traini, L.: An empirical study on code coverage of performance testing. In: Proceedings of the 28th EASE (2024) 24. Imran, M., Cortellessa, V., Di Ruscio, D., Rubei, R., Traini, L.: Is code coverage of performance tests related to source code features? an empirical study on open- source java systems. Empirical Software Engineering 30(6), 157 (2025) 25. Imran, M., Stoico, V., Malavolta, I.: Replication package for estimating energy usage, https://github.com/imran9pk/replication-package_method_energy_java 26. Jiarpakdee, J., Tantithamthavorn, C., Treude, C.: Autospearman: Automatically mitigating correlated software metrics for interpreting defect models (2018) 16Muhammad Imran, Vincenzo Stoico, and Ivano Malavolta 27. Karsten, M., Calin Dragomir, A., Apsan, R., Stoico, V., Malavolta, I.: Exper- iment runner: A tool for the automatic orchestration of experiments target- ing software systems. Science of Computer Programming 252, 103415 (2026). https://doi.org/10.1016/j.scico.2025.103415 28. Kifetew, F., Prandi, D., Susi, A.: On the energy consumption of test generation. In: 2025 IEEE Conference on Software Testing, Verification and Validation (2025) 29. von Kistowski, J., Block, H., Beckett, J., Spradling, C., Lange, K.D., Kounev, S.: Variations in cpu power consumption. In: Proceedings of the 7th ACM/SPEC on International Conference on Performance Engineering. p. 147â158 (2016) 30. Kruglov, A., Succi, G.: Developing sustainable and energy-efficient software sys- tems. Springer Nature (2023) 31. Kumar, M., Li, Y., Shi, W.: Energy consumption in java: An early experience. In: Eighth International Green and Sustainable Computing Conference (IGSC) (2017) 32. Laaber, C., Basmaci, M., Salza, P.: Predicting unstable software benchmarks using static source code features. Empirical Software Engineering 26(6), 114 (2021) 33. Lacoste, A., Luccioni, A., Schmidt, V., Dandres, T.: Quantifying the carbon emis- sions of machine learning. arXiv preprint arXiv:1910.09700 (2019) 34. Malavolta, I., Stoico, V., Lago, P.: Handbook on Teaching Empirical Software Engineering, chap. Ten Years of Teaching Empirical Software Engineering in the context of Energy-efficient Software. Springer Nature Switzerland (2024) 35. Manner, J.: Black softwareâthe energy unsustainability of software systems in the 21st century. Oxford Open Energy 2, oiac011 (2023) 36. Noureddine, A.: Powerjoular and joularjx: Multi-platform software power monitor- ing tools. In: 18th International Conference on Intelligent Environments (2022) 37. Noureddine, A., Le Goaer, O.: Investigating the impact of software design patterns on energy consumption. In: ICSA. p. 153â163. IEEE (2025) 38. Oliveira, W., Oliveira, R., Castor, F., Pinto, G., Fernandes, J.P.: Improving energy- efficiency by recommending java collections. Empirical Software Engineering (2021) 39. Oliveira, W., Torres, W., Castor, F., Ximenes, B.H.: Native or web? a preliminary study on the energy consumption of android development models. In: 2016 IEEE 23rd International Conference on Software Analysis, Evolution, and Reengineering (SANER). vol. 1, p. 589â593. IEEE (2016) 40. Pedregosa, F., Varoquaux: Scikit-learn: SelectKBest (2011), https://scikit-learn. org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html 41. Pereira, R., Couto, M., Ribeiro, F., Rua, R., Cunha, J., Fernandes, J.P., Saraiva, J.: Energy efficiency across programming languages: how do energy, time, and memory relate? In: Proceedings of the 10th ACM SLE. p. 256â267 (2017) 42. Poy, O., Moraga, M.Ă., GarcĂa, F., Calero, C.: Impact on energy consumption of design patterns, code smells and refactoring techniques: A systematic mapping study. Journal of Systems and Software p. 112303 (2024) 43. Schuler, A., Kotsis, G.: A systematic review on techniques and approaches to es- timate mobile software energy consumption. Sustainable Computing: Informatics and Systems 41, 100919 (2024) 44. scikit-learn developers: scikit-learn documentation, https://scikit-learn.org/ stable/modules/generated/sklearn.feature_selection.VarianceThreshold.html 45. Shajii, A., Ramirez, G., SmajloviÄ, H., Ray, J., Berger, B., Amarasinghe, S., Nu- managiÄ, I.: Codon: A compiler for high-performance pythonic applications and dsls. In: Proceedings of the 32nd ACM C (2023) 46. Stoico, V., Dragomir, A.C., Lago, P.: An empirical study on the performance and energy usage of compiled python code. In: Proceedings of the 29th International Conference on Evaluation and Assessment in Software Engineering (2025)