Last active
February 21, 2017 23:59
-
-
Save lbmn/d424dd0c8c85fa195743356fc133235a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, nre, times, tables, strutils | |
var benchmarkCycle = newTable[string,int64]() | |
var benchmarkEpoch = newTable[string,float]() | |
proc thousandsSep[T](num: T, sepChar=','): string = | |
return ($num).replace(re"(\d)(?=(\d{3})+(?!\d))", "$1"&sepChar) | |
proc rdtsc(): int64 = | |
when not defined(amd64): | |
return 0 | |
else: | |
var hi, lo: uint32 | |
asm """ | |
rdtsc | |
:"=a"(`lo`), "=d"(`hi`) | |
""" | |
result = int64(lo) or (int64(hi) shl 32) | |
template benchmark(benchmarkName: string, code: untyped) = | |
let | |
startEpoch = epochTime() | |
startCycle = rdtsc() | |
code | |
let | |
endCycle = rdtsc() | |
endEpoch = epochTime() | |
if not benchmarkCycle.hasKey(benchmarkName): | |
benchmarkCycle[benchmarkName] = 0 | |
benchmarkEpoch[benchmarkName] = 0.0 | |
benchmarkCycle[benchmarkName] += (endCycle - startCycle) | |
benchmarkEpoch[benchmarkName] += (endEpoch - startEpoch) | |
proc summary() = | |
echo "" | |
for benchmarkName in benchmarkCycle.keys: | |
let cycleStr = thousandsSep(benchmarkCycle[benchmarkName]) | |
let epochStr = benchmarkEpoch[benchmarkName].formatFloat(ffDecimal, 9) | |
echo "`$#` took $# cycles ($# sec)" % | |
[benchmarkName, cycleStr, epochStr] | |
proc exitSummary() {.noconv.} = | |
echo "\n\nOK, final score:" | |
summary() | |
var | |
minName = "" | |
minCycle = high(int64) | |
for benchmarkName, cycle in benchmarkCycle.pairs(): | |
if cycle < minCycle: | |
minName = benchmarkName | |
minCycle = cycle | |
if minCycle > 0: | |
echo "\nZOMG! " & minName.toUpperAscii & " WINS!!!" | |
quit 0 | |
proc veryStupidSampleBenchmarks() = | |
var | |
j = 0 | |
testCount = 0 | |
const | |
x = 100000 | |
while true: | |
inc testCount | |
j = 0 | |
benchmark "function": | |
for i in countup(1, x): | |
inc j | |
j = 0 | |
benchmark "operator": | |
for i in 1..x: | |
j = j + 1 | |
if testCount mod 1000 == 0: | |
summary() | |
when isMainModule: | |
setControlCHook exitSummary | |
echo "Benchmarking, press Ctrl-C to exit..." | |
veryStupidSampleBenchmarks() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment