Skip to content

Instantly share code, notes, and snippets.

@guitarrapc guitarrapc/benchmark.ps1
Last active Aug 17, 2019

Embed
What would you like to do?
benchmark: calculate sum of odd number with powershell
function benchmark([scriptblock]$Sb, [int]$Repeat, [string]$Way) {
[double]$tmp = 0
for ($i = 0; $i -lt $Repeat; $i++) {
$tmp += (Measure-Command $Sb).TotalMilliSeconds
}
[Console]::WriteLine("$Way | $Repeat | {0:0.000}", $($tmp / $Repeat))
}
Write-Host "BenchMark(Method) | Times | Avg(ms)
---- | ---- | ----"
benchmark -Sb { (1..100).Where{ ($_ -band 1) -eq 0 } | Measure -Sum } -Repeat 1000 -Way bitwise
benchmark -Sb { (1..100).Where{ [int]($_ / 2) * 2 -eq $_ } | Measure -Sum } -Repeat 1000 -Way division
benchmark -Sb { (1..100).Where{ $_ % 2 -eq 0 } | Measure -Sum } -Repeat 1000 -Way modulo
benchmark -Sb { (1..100).where{ ($_ -shr 1) -shl 1 -eq $_ } | Measure -Sum } -Repeat 1000 -Way shift
Write-Host ""
Write-Host "Benchmark(Pipeline) | Times | Avg(ms)
---- | ---- | ----"
benchmark -Sb { 1..100 | Where { ($_ -band 1) -eq 0 } | Measure -Sum } -Repeat 1000 -Way bitwise
benchmark -Sb { 1..100 | Where { [int]($_ / 2) * 2 -eq $_ } | Measure -Sum } -Repeat 1000 -Way division
benchmark -Sb { 1..100 | Where { $_ % 2 -eq 0 } | Measure -Sum } -Repeat 1000 -Way modulo
benchmark -Sb { 1..100 | where { ($_ -shr 1) -shl 1 -eq $_ } | Measure -Sum } -Repeat 1000 -Way shift
@guitarrapc

This comment has been minimized.

Copy link
Owner Author

guitarrapc commented Aug 17, 2019

BenchMark(Method) Times Avg(ms)
bitwise 1000 0.542
division 1000 0.521
modulo 1000 0.489
shift 1000 0.520
Benchmark(Pipeline) Times Avg(ms)
bitwise 1000 1.353
division 1000 1.486
modulo 1000 1.330
shift 1000 1.359
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.