-
Notifications
You must be signed in to change notification settings - Fork 184
Add performance sampler to record cpu and memory usage during execution #178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zhangt2333
wants to merge
12
commits into
master
Choose a base branch
from
zhangt2333/performance-sampler
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
80cf97f
Add performance sampler to record cpu and memory usage during execution
zhangt2333 26ddbf9
Disable by default
zhangt2333 64f1942
Rename variables
zhangt2333 162d910
Use record
zhangt2333 8ac0b7a
Add state checking
zhangt2333 cf083e9
Rename variables
zhangt2333 994246e
Minors
zhangt2333 484b797
Add docs
zhangt2333 6475508
Refactor build information retrieval
zhangt2333 4d4dbdf
Merge branch 'master' into zhangt2333/performance-sampler
zhangt2333 30b30e0
Add output file content test
zhangt2333 e875f5d
Merge branch 'master' into zhangt2333/performance-sampler
zhangt2333 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,231 @@ | ||
/* | ||
* Tai-e: A Static Analysis Framework for Java | ||
* | ||
* Copyright (C) 2022 Tian Tan <[email protected]> | ||
* Copyright (C) 2022 Yue Li <[email protected]> | ||
* | ||
* This file is part of Tai-e. | ||
* | ||
* Tai-e is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Lesser General Public License | ||
* as published by the Free Software Foundation, either version 3 | ||
* of the License, or (at your option) any later version. | ||
* | ||
* Tai-e is distributed in the hope that it will be useful,but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | ||
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General | ||
* Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public | ||
* License along with Tai-e. If not, see <https://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package pascal.taie.util; | ||
|
||
import com.fasterxml.jackson.annotation.JsonProperty; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.fasterxml.jackson.databind.SerializationFeature; | ||
import com.sun.management.OperatingSystemMXBean; | ||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
|
||
import java.io.File; | ||
import java.io.IOException; | ||
import java.lang.management.ManagementFactory; | ||
import java.lang.management.MemoryMXBean; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.ScheduledExecutorService; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
/** | ||
* Performance sampler for collecting system and JVM performance metrics during execution. | ||
* Supports automatic sampling at configurable intervals and outputs data in JSON format. | ||
*/ | ||
public class PerformanceSampler { | ||
|
||
private static final Logger logger = LogManager.getLogger(PerformanceSampler.class); | ||
|
||
public static final String OUTPUT_FILE = "tai-e-performance.json"; | ||
|
||
/** | ||
* Sampling interval in seconds | ||
*/ | ||
private static final int INTERVAL = 1; | ||
|
||
private final File outputFile; | ||
|
||
private final ScheduledExecutorService scheduler; | ||
|
||
private final OperatingSystemMXBean osBean; | ||
|
||
private final MemoryMXBean memoryBean; | ||
|
||
private final List<Sample> samples; | ||
|
||
/** | ||
* Start time of the performance sampling. | ||
* <code>-1</code> indicates that sampling has not started yet. | ||
*/ | ||
private long startTime = -1; | ||
|
||
/** | ||
* Finish time of the performance sampling. | ||
* <code>-1</code> indicates that sampling has not finished yet. | ||
*/ | ||
private long finishTime = -1; | ||
|
||
/** | ||
* Creates a new PerformanceSampler instance. | ||
*/ | ||
public PerformanceSampler(File outputDir) { | ||
this.outputFile = new File(outputDir, OUTPUT_FILE); | ||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> { | ||
Thread t = new Thread(r, this.getClass().getName()); | ||
t.setDaemon(true); | ||
return t; | ||
}); | ||
this.osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); | ||
this.memoryBean = ManagementFactory.getMemoryMXBean(); | ||
this.samples = new ArrayList<>(); | ||
} | ||
|
||
/** | ||
* Starts performance sampling. Records start time and begins periodic sampling. | ||
*/ | ||
public void start() { | ||
if (startTime != -1) { | ||
throw new IllegalStateException("Performance sampling has already started"); | ||
} | ||
this.startTime = System.currentTimeMillis(); | ||
scheduler.scheduleAtFixedRate(this::collectSample, | ||
0, INTERVAL, TimeUnit.SECONDS); | ||
} | ||
|
||
/** | ||
* Stops performance sampling, records finish time, and saves results to JSON file. | ||
*/ | ||
public void stop() { | ||
if (startTime == -1) { | ||
throw new IllegalStateException("Performance sampling has not started yet"); | ||
} | ||
if (finishTime != -1) { | ||
throw new IllegalStateException("Performance sampling has already finished"); | ||
} | ||
this.finishTime = System.currentTimeMillis(); | ||
scheduler.shutdown(); | ||
try { | ||
if (!scheduler.awaitTermination(2, TimeUnit.SECONDS)) { | ||
zhangt2333 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
scheduler.shutdownNow(); | ||
} | ||
} catch (InterruptedException e) { | ||
scheduler.shutdownNow(); | ||
Thread.currentThread().interrupt(); | ||
} | ||
saveToFile(); | ||
} | ||
|
||
/** | ||
* Collects a single performance sample including CPU and memory usage. | ||
*/ | ||
private void collectSample() { | ||
try { | ||
long timestamp = System.currentTimeMillis(); | ||
|
||
// Get CPU usage and handle negative values indicating unavailable data | ||
double processCpuUsage = osBean.getProcessCpuLoad(); | ||
if (processCpuUsage < 0) { | ||
processCpuUsage = 0.0; | ||
} | ||
double systemCpuUsage = osBean.getCpuLoad(); | ||
if (systemCpuUsage < 0) { | ||
systemCpuUsage = 0.0; | ||
} | ||
|
||
// Get JVM process memory usage (heap + non-heap) | ||
long heapMemoryUsed = memoryBean.getHeapMemoryUsage().getUsed(); | ||
long nonHeapMemoryUsed = memoryBean.getNonHeapMemoryUsage().getUsed(); | ||
long processMemoryUsedMB = (heapMemoryUsed + nonHeapMemoryUsed) / (1024 * 1024); | ||
|
||
// Get total system memory usage | ||
long totalMemory = osBean.getTotalMemorySize(); | ||
long freeMemory = osBean.getFreeMemorySize(); | ||
long systemMemoryUsedMB = (totalMemory - freeMemory) / (1024 * 1024); | ||
|
||
Sample sample = new Sample(timestamp, processCpuUsage, | ||
systemCpuUsage, processMemoryUsedMB, systemMemoryUsedMB); | ||
|
||
synchronized (samples) { | ||
samples.add(sample); | ||
} | ||
} catch (Exception e) { | ||
zhangt2333 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Log error but continue sampling | ||
logger.error("Error collecting performance sample: {}", e.getMessage()); | ||
zhangt2333 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
/** | ||
* Saves performance data to JSON file. | ||
*/ | ||
private void saveToFile() { | ||
logger.info("Saving performance report to: {}", outputFile); | ||
try { | ||
String version = RuntimeInfoLogger.getVersion(); | ||
String commit = RuntimeInfoLogger.getCommit(); | ||
String operatingSystem = System.getProperty("os.name") | ||
+ " (" + System.getProperty("os.arch") + ")"; | ||
String javaRuntime = System.getProperty("java.vendor") | ||
+ " " + System.getProperty("java.runtime.name") | ||
+ " " + System.getProperty("java.runtime.version"); | ||
String username = System.getProperty("user.name"); | ||
int cpuCores = Runtime.getRuntime().availableProcessors(); | ||
long memoryMB = osBean.getTotalMemorySize() / (1024 * 1024); | ||
long startTime = this.startTime; | ||
long finishTime = this.finishTime; | ||
List<Sample> samples; | ||
synchronized (this.samples) { | ||
samples = new ArrayList<>(this.samples); | ||
} | ||
|
||
PerformanceReport report = new PerformanceReport( | ||
version, commit, operatingSystem, javaRuntime, | ||
username, cpuCores, memoryMB, startTime, | ||
finishTime, samples); | ||
|
||
ObjectMapper mapper = new ObjectMapper(); | ||
mapper.enable(SerializationFeature.INDENT_OUTPUT); | ||
mapper.writeValue(outputFile, report); | ||
} catch (IOException e) { | ||
logger.error("Failed to write performance report: {}", e.getMessage()); | ||
} | ||
} | ||
|
||
/** | ||
* Main performance report structure for JSON serialization. | ||
*/ | ||
private record PerformanceReport( | ||
@JsonProperty("version") String version, | ||
@JsonProperty("commit") String commit, | ||
@JsonProperty("operatingSystem") String operatingSystem, | ||
@JsonProperty("javaRuntime") String javaRuntime, | ||
@JsonProperty("username") String username, | ||
@JsonProperty("cpuCores") int cpuCores, | ||
@JsonProperty("memoryMB") long memoryMB, | ||
@JsonProperty("startTime") long startTime, | ||
@JsonProperty("finishTime") long finishTime, | ||
@JsonProperty("samples") List<Sample> samples) { | ||
} | ||
|
||
/** | ||
* Individual performance sample data point. | ||
*/ | ||
private record Sample( | ||
@JsonProperty("timestamp") long timestamp, | ||
@JsonProperty("processCpuUsage") double processCpuUsage, | ||
@JsonProperty("systemCpuUsage") double systemCpuUsage, | ||
@JsonProperty("processMemoryUsedMB") long processMemoryUsedMB, | ||
@JsonProperty("systemMemoryUsedMB") long systemMemoryUsedMB) { | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
src/test/java/pascal/taie/analysis/pta/PointerAnalysisResultTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,25 @@ | ||
/* | ||
* Tai-e: A Static Analysis Framework for Java | ||
* | ||
* Copyright (C) 2022 Tian Tan <[email protected]> | ||
* Copyright (C) 2022 Yue Li <[email protected]> | ||
* | ||
* This file is part of Tai-e. | ||
* | ||
* Tai-e is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Lesser General Public License | ||
* as published by the Free Software Foundation, either version 3 | ||
* of the License, or (at your option) any later version. | ||
* | ||
* Tai-e is distributed in the hope that it will be useful,but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | ||
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General | ||
* Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public | ||
* License along with Tai-e. If not, see <https://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package pascal.taie.analysis.pta; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
56 changes: 56 additions & 0 deletions
56
src/test/java/pascal/taie/util/PerformanceSamplerTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/* | ||
* Tai-e: A Static Analysis Framework for Java | ||
* | ||
* Copyright (C) 2022 Tian Tan <[email protected]> | ||
* Copyright (C) 2022 Yue Li <[email protected]> | ||
* | ||
* This file is part of Tai-e. | ||
* | ||
* Tai-e is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Lesser General Public License | ||
* as published by the Free Software Foundation, either version 3 | ||
* of the License, or (at your option) any later version. | ||
* | ||
* Tai-e is distributed in the hope that it will be useful,but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | ||
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General | ||
* Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public | ||
* License along with Tai-e. If not, see <https://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package pascal.taie.util; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
import java.io.File; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
||
class PerformanceSamplerTest { | ||
|
||
@Test | ||
void unitTest() throws InterruptedException { | ||
File outputDir = new File("output"); | ||
File outputFile = new File(outputDir, PerformanceSampler.OUTPUT_FILE); | ||
outputFile.delete(); | ||
PerformanceSampler sampler = new PerformanceSampler(outputDir); | ||
sampler.start(); | ||
Thread.sleep(1000); | ||
sampler.stop(); | ||
assertTrue(outputFile.exists()); | ||
} | ||
|
||
@Test | ||
void integrationTest() { | ||
pascal.taie.Main.main( | ||
"--performance-sampling", | ||
"-pp", | ||
"-cp", "src/test/resources/pta/basic", | ||
"-m", "New", | ||
"-a", "pta=implicit-entries:false;only-app:true;" | ||
); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.