Last active
August 17, 2019 10:43
-
-
Save guitarrapc/04df00c23ca58f276fd694b41b87b27a to your computer and use it in GitHub Desktop.
benchmark: calculate sum of odd number with powershell
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
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 |
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