Skip to content

Commit

Permalink
Always stop timers when exiting the 'Timer.time' block
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyle Rokos committed Jun 11, 2024
1 parent 03225d2 commit 2b4a12b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
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

0 comments on commit 2b4a12b

Please sign in to comment.