Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to benchmark few lines of code in nim?

Tags:

nim-lang

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
like image 693
exebook Avatar asked Apr 12 '16 15:04

exebook


2 Answers

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.

like image 194
zah Avatar answered Nov 13 '22 23:11

zah


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.

like image 23
def- Avatar answered Nov 13 '22 23:11

def-