我需要在两个不同的语料库上对两个不同的程序进行基准测试,为了获得更准确的读数,我想在循环中运行基准测试并获取每个基准测试的平均执行时间。为了简化自己,我编写了以下PowerShell函数:
Function Benchmark {
Param($progPath, $benchmarkPath, $iters=27)
$time = (Measure-Command { & "$progPath" "$benchmarkPath" }).TotalSeconds
$sum = $lowest = $highest = $time
for($i = 1; $i -lt $iters; $i++) {
$time = (Measure-Command { & "$progPath" "$benchmarkPath" }).TotalSeconds
$sum += $time
if($time -lt $lowest) { $lowest = $time }
elseif($time -gt $highest) {$highest = $time }
}
$sum -= ($lowest + $highest)
$sum / ($iters - 2)
}
理论上,这应该执行作为$progPath
中的命令提供的程序,其中$benchmarkPath
中的基准测试脚本作为其参数,但是当我像这样运行它时,我得到以下结果:< / p>
PS > $nonPrivateBenchmark = Benchmark(".\Python\PCbuild\amd64\python", ".\Benchmarks\non_private_access.py")
& : The term '.\Python\PCbuild\amd64\python .\Benchmarks\non_private_access.py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:3 char:30
+ $time = (Measure-Command { & "$progPath" "$benchmarkPath" }).TotalSeconds
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\Python\PCbuil...ivate_access.py:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
(加上26次重复相同的错误,但在第6行。)
但是,如果分配三个参数参数并将剩余的函数体直接复制到PowerShell中,它可以工作并将$nonPrivateAccess
设置为合理的值:
$progPath = ".\Python\PCbuild\amd64\python"
$benchmarkPath = ".\Benchmarks\non_private_access.py"
$iters = 27
$time = (Measure-Command { & "$progPath" "$benchmarkPath" }).TotalSeconds
$sum = $lowest = $highest = $time
for($i = 1; $i -lt $iters; $i++) {
$time = (Measure-Command { & "$progPath" "$benchmarkPath" }).TotalSeconds
$sum += $time
if($time -lt $lowest) { $lowest = $time }
elseif($time -gt $highest) {$highest = $time }
}
$sum -= ($lowest + $highest)
$nonPrivateBenchmark = $sum / ($iters - 2)
我通过实验得出结论,问题是"$progPath" "$benchmarkPath"
在用'.\Python\PCbuild\amd64\python .\Benchmarks\non_private_access.py'
运算符执行之前连接成单个字符串&
,并且将它们分隔的空格被解释为一部分命令名称,使PowerShell尝试将整个字符串作为单个命令执行(无法执行)。我试过在参数参数的周围和内部放置转义引号,但无济于事。还有其他人有解决这个问题的方法吗?
PS: 相当广泛的搜索只给了我很多与人有相反问题的点击。可能是因为我激活了一些非默认的PowerShell设置,使得它过于积极地解析空间?
答案 0 :(得分:1)
Benchmark(".\Python\PCbuild\amd64\python", ".\Benchmarks\non_private_access.py")
此语法将数组传递给Benchmark函数的第一个参数,然后在将其用作命令时将其转换为单个字符串。这实际上与:
相同Benchmark ".\Python\PCbuild\amd64\python", ".\Benchmarks\non_private_access.py"
将多个参数传递给PowerShell函数的常规语法是在参数之间放置一个空格:
Benchmark ".\Python\PCbuild\amd64\python" ".\Benchmarks\non_private_access.py"
您还可以使用参数名称:
Benchmark -progPath ".\Python\PCbuild\amd64\python" -benchmarkPath ".\Benchmarks\non_private_access.py"