Skip to content
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

Always stop timers when exiting the 'Timer.time' block #374

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ class Timer constructor(val name: String) {
}
}

/**
* Functional interface for Java Interoperability that allows throwing an exception
* from the closure.
*/
fun interface ThrowingFn<T> {
@Throws(Exception::class)
fun execute(): T?
}

/**
* Times the function / closure. The time is not returned but can be graphed using the
* [graph] function.
Expand All @@ -66,11 +75,13 @@ class Timer constructor(val name: String) {
* @param fn The function or closure to time
* @return The result of [fn]
*/
fun <T> time(name: String, fn: () -> T?): T? {
fun <T> time(name: String, fn: ThrowingFn<T>): T? {
val timer = Timer(name)
val returnValue = fn()
timer.stop()
return returnValue
try {
return fn.execute()
} finally {
timer.stop()
}
}

private enum class LineStyle(val horizontalChar: String, val junctionChar: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

class TimerKtTest {
Expand All @@ -27,6 +28,23 @@ public void time() {
assertEquals(5, i);
}

@Test
public void timeException() {
// This adds a timer to the graph, but we can't access the timer directly
try {
Integer i = Timing.time("Timer 1", () -> {
sleep(sleep1Duration);
throw new Exception("exception");
});
} catch (Exception e) {
// do nothing
}
Timer.Companion.getTimers$integration_sdk_adapter_library().forEach((item) -> {
assertNotNull(item.getEndTime$integration_sdk_adapter_library());
});

}

@Test
public void getDuration() {
Timer timer = new Timer("Timer");
Expand Down
Loading