我如何 运行 一个批处理文件大约 1000 次,之后我想要平均执行时间作为输出。这可能吗?

How can I run a batch-file about 1000 times, afterwards I want the average execution time as a output. Is this possible?

我尝试执行 powershell 命令,但随后 1000 windows 打开并且 powershell ISE 崩溃了。有没有办法在后台 运行 批处理文件 1000 次?有没有更聪明的方法可以得出平均执行时间?

这是我试过的代码:

cd C:\scripts
Measure-Command { 
    for($i = 0;$i -lt 1000;$i++){
      Start-Process -FilePath "C:\scripts\open.bat"
    }
}

Start-Process 默认 运行s 程序 异步 ,在 新控制台 window .

因为你想运行你的批处理文件同步,在same控制台window,调用它 直接 (其中,因为路径是双引号的 - 尽管在这种情况下它并不严格必须是 - 需要 &call operator 对于语法原因):

Measure-Command { 
    foreach ($i in 1..1000){
      & "C:\scripts\open.bat"
    }
}

注意:Measure-Command 丢弃脚本块中的成功输出 运行;如果您确实想在控制台中看到它,请使用以下变体,但请注意它会减慢处理速度:

Measure-Command { 
    & {
      foreach ($i in 1..1000){
        & "C:\scripts\open.bat"
      }
    } | Out-Host
}

This answer 更详细地解释了 为什么 Start-Process 通常是调用基于控制台的程序 和脚本的错误工具。


Measure-Command 是 PowerShell 中性能测量的正确工具,但重要的是要注意,考虑到 PowerShell 的动态特性,这种测量远非一门精确的科学,它涉及许多缓存和背后的按需编译场景。

取多个 运行 的平均值通常是有意义的,尤其是在调用 外部程序时 ;相比之下,如果 PowerShell 代码 被重复执行并且重复次数超过 16 次,则会发生按需编译并加速后续执行,这可能会使结果出现偏差。

Time-CommandMeasure-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:\scripts\open.bat" }

请注意,虽然 Time-Command 是一个方便的包装器,甚至可以用于测量 单个 命令的性能,它还允许您 比较 多个命令的性能,作为单独的script blocks ({ ... }).

传递

[1] 假设你已经查看了链接的 Gist 的源代码以确保它是安全的(我个人可以向你保证,但你应该经常检查),你可以直接安装它如下:
irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex