Last active
September 23, 2022 15:46
-
-
Save docwhat/c8f9570308a7234f0fac811a0bfe82d0 to your computer and use it in GitHub Desktop.
In Groovy profiling
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
#!/usr/bin/env groovy | |
// This works in Jenkinsfiles without approving any scripts. | |
class MyProfiler { | |
def timings | |
def dsl | |
MyProfiler(dsl) { | |
this.timings = [:] | |
this.dsl = dsl | |
} | |
void echo(String str) { | |
try { | |
this.dsl.echo(str) | |
} catch(_) { | |
println(str) | |
} | |
} | |
Number measure(String name = 'default', Closure closure) { | |
echo("⏱ (${name}): measuring...") | |
def start = System.currentTimeMillis() | |
closure() | |
def stop = System.currentTimeMillis() | |
def duration = stop - start | |
echo("⏱ (${name}): ${String.format("%,d", duration)}ms") | |
this.timings[name] = duration | |
return duration | |
} | |
String toString() { | |
this.timings.toString() | |
} | |
Number total() { | |
this.timings.collect { it.value }.sum() | |
} | |
void display() { | |
List<String> out = [] | |
this.timings.each { name, duration -> | |
out.add " ∑ ${String.format("%,10d", duration)}ms (${name})" | |
} | |
out.add " ∑ Total: ${String.format("%,d", total())}ms" | |
echo out.join("\n") | |
} | |
} | |
p = new MyProfiler(this) | |
p.measure('first') { | |
sleep 1 | |
} | |
p.measure('second') { | |
sleep 2 | |
} | |
p.measure('first') { | |
sleep 1 | |
} | |
p.measure('second') { | |
sleep 2 | |
} | |
p.display() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment