Category talk:Wren-check: Difference between revisions

→‎Source code: Added Benchmark class.
(→‎Source code: Added an overload for Check.type method to cater for custom error messages.)
(→‎Source code: Added Benchmark class.)
Line 297:
 
static ok(condition) { ok(condition, "Condition is not met.") }
}
 
/*
Benchmark is a class containing static methods to report
how fast a piece of code runs over a given number of iterations.
*/
class Benchmark {
// Private helper method to format results to 3 decimal places.
static fmt_(s) {
s = s.toString
var len = s.count
var ix = s.indexOf(".")
if (ix == len - 4) return s
if (ix == len - 3) return s + "0"
if (ix == len - 2) return s + "00"
if (ix == -1) return s + ".000"
return s[0..ix+3]
}
 
// Returns how fast 'fn' runs (best, mean, worst) over 'iter' iterations
// in milliseconds rounded to 3 decimal places.
// If 'print' is true, prints the results to the terminal in a fixed format.
static run(name, iter, print, fn) {
Check.str("Name", name, 1)
Check.posInt("Iterations", iter)
Check.func("Function", fn, 0)
var best
var worst
var sum = 0
for (i in 1..iter) {
var start = System.clock
fn.call()
var time = System.clock - start
sum = sum + time
if (i == 1) {
best = time
worst = time
} else if (time < best) {
best = time
} else if (time > worst) {
worst = time
}
}
best = (best * 1e6).round/ 1e3
worst = (worst * 1e6).round / 1e3
var mean = (sum/iter * 1e6).round / 1e3
if (print) {
var title = "Running '%(name)' over %(iter) iteration(s):"
System.print(title)
System.print("-" * title.count)
System.print("Best %(fmt_(best)) ms")
System.print("Mean %(fmt_(mean)) ms")
System.print("Worst %(fmt_(worst)) ms\n")
}
return [best, mean, worst]
}
}</lang>
9,476

edits