I read this down and up: http://nim-lang.org/docs/times.html
But still cannot figure the simple thing: how to get time in ms twice, once before my code, and again after my code runs, and then print the difference?
I tried their example:
var t0 = cpuTime()
sleep(300)
echo "CPU time [s] ", cpuTime() - t0
But this prints something meaningless:
CPU time [s] 4.200000000000005e-05
If you plan to perform a lot of measurements, the best approach is to create a re-usable helper template, abstracting away the timing code:
import times, os, strutils
template benchmark(benchmarkName: string, code: untyped) =
block:
let t0 = epochTime()
code
let elapsed = epochTime() - t0
let elapsedStr = elapsed.formatFloat(format = ffDecimal, precision = 3)
echo "CPU Time [", benchmarkName, "] ", elapsedStr, "s"
benchmark "my benchmark":
sleep 300
This will print out
CPU Time [my benchmark] 0.305s
If you need more comprehensive data about the performance of all of the code included in your project, Nim offers a special build mode, which instruments the compiled code with profiling probes. You can find more about it here:
http://nim-lang.org/docs/estp.html
Lastly, since Nim generates C code with C function names that directly correspond to their Nim counterparts, you can use any C profiler with Nim programs.
cpuTime
only calculates the time the CPU actually spends on the process, at least on Linux. So the entire sleeping time doesn't count. You can use epochTime
instead, which is the actual UNIX timestamp with subsecond accuracy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With