Last active
August 17, 2019 17:40
-
-
Save guitarrapc/2eb9005aa441b217a2d99f6e90ddacb9 to your computer and use it in GitHub Desktop.
Calculate sum of odd by powershell class
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)) | |
} | |
class Calc { | |
static [int] StaticSumOddBitwise() { | |
return ((1..100).Where{ ($_ -band 1) -eq 0 } | Measure -Sum).Sum | |
} | |
static [int] StaticSumOddDivision() { | |
return ((1..100).Where{ [int]($_ / 2) * 2 -eq $_ } | Measure -Sum ).Sum | |
} | |
static [int] StaticSumOddModulo() { | |
return ((1..100).Where{ ($_ -band 1) -eq 0 } | Measure -Sum).Sum | |
} | |
static [int] StaticSumOddShift() { | |
return ((1..100).where{ ($_ -shr 1) -shl 1 -eq $_ } | Measure -Sum).Sum | |
} | |
[int] SumOddBitwise() { | |
return ((1..100).Where{ ($_ -band 1) -eq 0 } | Measure -Sum).Sum | |
} | |
[int] SumOddDivision() { | |
return ((1..100).Where{ [int]($_ / 2) * 2 -eq $_ } | Measure -Sum ).Sum | |
} | |
[int] SumOddModulo() { | |
return ((1..100).Where{ ($_ -band 1) -eq 0 } | Measure -Sum).Sum | |
} | |
[int] SumOddShift() { | |
return ((1..100).where{ ($_ -shr 1) -shl 1 -eq $_ } | Measure -Sum).Sum | |
} | |
} | |
Write-Host "Benchmark(Class) | Times | Avg(ms) | |
---- | ---- | ----" | |
$calc = [Calc]::new() | |
benchmark -Sb { $calc.SumOddBitwise() } -Repeat 1000 -Way bitwise | |
benchmark -Sb { $calc.SumOddDivision() } -Repeat 1000 -Way division | |
benchmark -Sb { $calc.SumOddModulo() } -Repeat 1000 -Way modulo | |
benchmark -Sb { $calc.SumOddShift() } -Repeat 1000 -Way shift | |
Write-Host "" | |
Write-Host "Benchmark(Static) | Times | Avg(ms) | |
---- | ---- | ----" | |
benchmark -Sb { [Calc]::StaticSumOddBitwise() } -Repeat 1000 -Way bitwise | |
benchmark -Sb { [Calc]::StaticSumOddDivision() } -Repeat 1000 -Way division | |
benchmark -Sb { [Calc]::StaticSumOddModulo() } -Repeat 1000 -Way modulo | |
benchmark -Sb { [Calc]::StaticSumOddShift() } -Repeat 1000 -Way shift |
Author
guitarrapc
commented
Aug 17, 2019
Benchmark(Class) | Times | Avg(ms) |
---|---|---|
bitwise | 1000 | 0.536 |
division | 1000 | 0.562 |
modulo | 1000 | 0.533 |
shift | 1000 | 0.559 |
Benchmark(Static) | Times | Avg(ms) |
---|---|---|
bitwise | 1000 | 0.538 |
division | 1000 | 0.553 |
modulo | 1000 | 0.521 |
shift | 1000 | 0.544 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment