How to benchmark few lines of code in nim?
Asked Answered
C

2

7

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
Capillary answered 12/4, 2016 at 15:22 Comment(0)
S
14

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.

Sulfapyridine answered 12/4, 2016 at 17:44 Comment(1)
Ey, i didn't know this profile. Nim is full of secrets.Dandrea
H
5

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.

Hardiness answered 12/4, 2016 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.