How to compare multiple lines of code in nim?

I read it up and down: http://nim-lang.org/docs/times.html

But still can't understand the simple thing: how to get the time in milliseconds twice, once before my code and again after my code, and then print the difference?

I tried my example:

var t0 = cpuTime() sleep(300) echo "CPU time [s] ", cpuTime() - t0 

But this prints something meaningless:

 CPU time [s] 4.200000000000005e-05 
+5
source share
2 answers

If you plan on doing a lot of measurements, the best approach is to create a reusable helper template that abstracts the synchronization code:

 import times, os, strutils template benchmark(benchmarkName: string, code: stmt) = 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 

Will open

 CPU Time [my benchmark] 0.305s 

If you need more complete performance data for all the code included in your project, Nim offers a special build mode that allows you to compile code using profiling probes. You can learn more about this here:

http://nim-lang.org/docs/estp.html

Finally, since Nim generates C code with names of C functions that directly correspond to their Nim counterparts, you can use any C profiler with Nim programs.

+8
source

cpuTime only calculates the CPU time spent on a process, at least on Linux. Thus, all sleep time is not taken into account. Instead, you can use epochTime , which is the actual UNIX timestamp accurate to the second.

+2
source

Source: https://habr.com/ru/post/1246962/


All Articles