Skip to content

Commit

Permalink
Implement ComplexityAnalyzer
Browse files Browse the repository at this point in the history
  • Loading branch information
amaldoror committed Jul 28, 2024
1 parent b08e13d commit 68b8f9f
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/main/java/org/rancore/utils/ComplexityAnalyzer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.rancore.utils;

public class ComplexityAnalyzer {

// Interface for a method that we want to analyze
@FunctionalInterface
public interface MethodToAnalyze {
void execute();
}

public static void analyze(MethodToAnalyze method) {
// Measure time complexity
long startTime = System.nanoTime();
method.execute();
long endTime = System.nanoTime();
long duration = endTime - startTime;

// Measure space complexity
Runtime runtime = Runtime.getRuntime();
runtime.gc(); // Call garbage collector to get more accurate measurement
long startMemory = runtime.totalMemory() - runtime.freeMemory();
method.execute();
long endMemory = runtime.totalMemory() - runtime.freeMemory();
long memoryUsed = endMemory - startMemory;

// Print results
System.out.println("Time taken: " + duration + " nanoseconds");
System.out.println("Memory used: " + memoryUsed + " bytes");
}

public static void main(String[] args) {
// Example usage:
analyze(() -> sumArray(new int[]{1, 2, 3, 4, 5}));
}

// Example method to analyze
public static int sumArray(int[] array) {
int sum = 0;
for (int num : array) {
sum += num;
}
return sum;
}
}

0 comments on commit 68b8f9f

Please sign in to comment.