Microsoft technet suggests [Math]::Floor([int]$a/[int]$b)
for integer division。我相信[int][Math]::Floor($a/$b)
由于少了一次投射操作,所以更具可读性和更高性能。 I have proven both methods equivalent.但是,我无法获得一致的结果。我的方法涉及重复两种方法10,000次并使用Measure-Command cmdlet测量结果。但是不能构建一个测试,其中一个测试反复执行比另一个测试更好。我的代码如下:性能测试PowerShell整数除法的两种方法
Write-Host
$loopLength = 10000
$runtime = Measure-Command {
1..$loopLength | ForEach-Object {
Foreach ($divisor in 2,3,5,7) {
[Math]::Floor([int]$_/[int]$divisor) > $null
}
}
}
"Double Cast: $($runtime.TotalMilliSeconds)"
$runtime = Measure-Command {
1..$loopLength | ForEach-Object {
Foreach ($divisor in 2,3,5,7) {
[int][Math]::Floor($_/$divisor) > $null
}
}
}
"Single Cast: $($runtime.TotalMilliSeconds)"
如何修改我的代码,所以我拿到证明一种方法比另一种更好的结果一致。
我认为你缺少'[INT] [数学] ::楼($ _/$除数)> $ null'从第二个循环。 – 2012-01-15 04:14:01
这些看起来在性能上如此接近,以至于系统的后台进程使差异变得可忽略不计。您可以通过停止服务,关闭窗口等来最小化背景噪音,甚至可以在Windows安全模式下启动。 (请参阅msconfig.exe)。我必须说,我不明白为什么施放操作的结果会使操作本身更快。 – 2012-01-15 04:34:06
@AndyArismendiquite权利和纠正。你可以自己编辑它并留下编辑注释。 – 2012-01-15 14:47:11