Skip to content

Instantly share code, notes, and snippets.

@docwhat
Last active September 23, 2022 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save docwhat/c8f9570308a7234f0fac811a0bfe82d0 to your computer and use it in GitHub Desktop.
Save docwhat/c8f9570308a7234f0fac811a0bfe82d0 to your computer and use it in GitHub Desktop.
In Groovy profiling
#!/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