37 lines
1.5 KiB
Java
37 lines
1.5 KiB
Java
/*
|
|
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
|
* Your use of it is subject to your agreement with Google.
|
|
*/
|
|
package com.example.util;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
import java.util.function.Supplier;
|
|
|
|
/**
|
|
* A utility class to measure and log the execution time of a given operation.
|
|
* It uses the Supplier functional interface to wrap the code block to be timed.
|
|
*/
|
|
public class PerformanceTimer {
|
|
private static final Logger logger = LoggerFactory.getLogger(PerformanceTimer.class);
|
|
|
|
|
|
public static <T> T timeExecution(String operationName, Supplier<T> operation) {
|
|
long startTime = System.nanoTime();
|
|
try {
|
|
T result = operation.get();
|
|
long endTime = System.nanoTime();
|
|
long durationNanos = endTime - startTime;
|
|
double durationMillis = durationNanos / 1_000_000.0;
|
|
logger.info("Operation '{}' completed in {} ms.", operationName, String.format("%.2f", durationMillis));
|
|
return result;
|
|
} catch (Exception e) {
|
|
long endTime = System.nanoTime();
|
|
long durationNanos = endTime - startTime;
|
|
double durationMillis = durationNanos / 1_000_000.0;
|
|
logger.error("Operation '{}' failed in {} ms: {}", operationName, String.format("%.2f", durationMillis), e.getMessage(), e);
|
|
throw new RuntimeException("Error during timed operation: " + operationName, e);
|
|
}
|
|
}
|
|
} |