如何才能将一个批处理文件运行大约1000次,之后我想要将平均执行时间作为输出。这个是可能的吗? [英] How can I run a batch-file about 1000 times, afterwards I want the average execution time as a output. Is this possible?
本文介绍了如何才能将一个批处理文件运行大约1000次,之后我想要将平均执行时间作为输出。这个是可能的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我尝试过的代码:
cd C:scripts
Measure-Command {
for($i = 0;$i -lt 1000;$i++){
Start-Process -FilePath "C:scriptsopen.bat"
}
}
推荐答案
Start-Process
默认情况下,在新的控制台窗口中异步运行程序。
由于您希望同步运行批处理文件,因此在相同的控制台窗口中,直接调用它(由于路径用双引号引起来--虽然在本例中并不严格是必须的--出于语法原因需要&
,call operator):
Measure-Command {
foreach ($i in 1..1000){
& "C:scriptsopen.bat"
}
}
注意:Measure-Command
丢弃正在运行的脚本块的成功输出;如果您确实希望在控制台中看到它,请使用以下变体,但请注意,它会减慢处理速度:
Measure-Command {
& {
foreach ($i in 1..1000){
& "C:scriptsopen.bat"
}
} | Out-Host
}
This answer更详细地解释为什么Start-Process
通常是调用基于控制台的程序和脚本的错误工具。
Measure-Command
是PowerShell中性能测量的正确工具,但必须注意的是,考虑到PowerShell的动态性质,它涉及许多缓存和幕后按需编译,因此此类测量远不是一门精确的科学。
平均多次运行通常是有意义的,特别是在调用外部程序时;相比之下,如果重复执行PowerShell代码并且重复次数超过16次,则会发生按需编译并加快后续执行速度,这可能会扭曲结果。
Time-Command
是Measure-Command
的友好包装器,可从this MIT-licensed Gist[1]获得;它可用于简化您的测试。
# Download and define function `Time-Command` on demand (will prompt).
# To be safe, inspect the source code at the specified URL first.
if (-not (Get-Command -ea Ignore Time-Command)) {
$gistUrl = 'https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1'
if ((Read-Host "`n====`n OK to download and define benchmark function ``Time-Command`` from Gist ${gistUrl}?`n=====`n(y/n)?").Trim() -notin 'y', 'yes') { Write-Warning 'Aborted.'; exit 2 }
Invoke-RestMethod $gistUrl | Invoke-Expression
if (-not ${function:Time-Command}) { exit 2 }
}
Write-Verbose -Verbose 'Running benchmark...'
# Omit -OutputToHost to run the commands quietly.
Time-Command -Count 1000 -OutputToHost { & "C:scriptsopen.bat" }
请注意,虽然Time-Command
即使对于测量单个命令的性能来说也是一个方便的包装器,但它也允许您比较多个命令的性能,这些命令作为单独的script blocks({ ... }
)传递。
[1]假设您已经查看了链接的Gist的源代码以确保它是安全的(我可以亲自向您保证,但您应该始终检查),您可以直接按如下方式安装它:
irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
这篇关于如何才能将一个批处理文件运行大约1000次,之后我想要将平均执行时间作为输出。这个是可能的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文