Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active August 17, 2019 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/04df00c23ca58f276fd694b41b87b27a to your computer and use it in GitHub Desktop.
Save guitarrapc/04df00c23ca58f276fd694b41b87b27a to your computer and use it in GitHub Desktop.
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
Copy link
Author

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