gpt4 book ai didi

multithreading - 如何保证对象在 Powershell 中实例化的顺序?

转载 作者:行者123 更新时间:2023-12-04 06:47:18 24 4
gpt4 key购买 nike

使用 Measure-Command 对代码块进行计时相当简单。 , [system.diagnostics.stopwatch]或通过区分几个 Get-Date电话,但这是奇怪的事情;

当我包装 Measure-Command有两个日期对象,有时是 Measure-Command.TotalMilliseconds长于 ($EndTime - $StartTime).TotalMilliSeconds .

$EndTimeMeasure-Command 之前实例化的对象完成?

如果我运行单线程,为什么仍然会发生这种情况; powershell.exe -sta ?

有没有办法强制$EndTimeMeasure-Command 之后设置结束?

有没有保证StartTime已在 Measure-Command 之前创建?

显然,这种特定方法不是评估代码执行时间的明智方法。

$Stopwatch = [system.diagnostics.stopwatch]::startNew() 
$mc =Measure-Command{Invoke-WebRequest -Uri "http://www.google.com" -Method Head}
$Stopwatch.stop()


$mc.TotalMilliseconds
$Stopwatch.Elapsed.TotalMilliSeconds
"="
$Stopwatch.Elapsed.TotalMilliSeconds - $mc.TotalMilliseconds


"`n"

$StartTime = (get-Date)
$mc = Measure-Command{Invoke-WebRequest -Uri "http://www.google.com" -Method Head}
$EndTime = (get-Date)

$mc.TotalMilliseconds
($EndTime - $StartTime).TotalMilliSeconds
"="
($EndTime - $StartTime).TotalMilliSeconds - $mc.TotalMilliseconds #This should never be negative but sometimes it is.

"`n"

$mc1 =Measure-Command{$mc2 = Measure-Command{Invoke-WebRequest -Uri "http://www.google.com" -Method Head}}

$mc1.TotalMilliseconds - $mc2.TotalMilliseconds

示例输出
122.3065
122.4322
=
0.125700000000009


142.8695
140.6371
=
-2.23240000000001


0.104199999999992

最佳答案

哦,男孩,这是很多有趣的问题,虽然我感觉你可能被误入歧途了,因为并非所有的测量方法都是平等的——所以让我们来看看吧!

Why does this still happen if I run single-threaded; powershell.exe -sta?



因为这不是线程或并发问题

Is there any way to force $EndTime to be set after Measure-Command ends?



是的,通过将它们分成单独的语句(正如你已经完成的那样)

Is there any guarantee $StartTime has been created before Measure-Command?



出于与上一个答案相同的根本原因;是的!

Clearly this particular method is not a sensible way to evaluate code execution time.



Aaaaaaand,你刚刚给了自己答案:)

DateTime.Now 是精确间隔测量的糟糕来源
Get-Date ,不指定任何参数,返回 DateTime.Now 的值

虽然 DateTime.Now返回 DateTime具有高精度的结构,它的值是通过向操作系统查询当前挂钟时间来获得的,并且这种交互不会产生与其潜在精度相称的准确结果 - 关于这方面的更多信息,我建议阅读这个 blog post by Eric Lippert

如果您使用以下方法对其进行测试,您可能会看到很多“抖动”而不是正态间隔分布:
$timestamp = Get-Date
0..9 |%{
$timestamp - ($timestamp = Get-Date)
} |Select Ticks

在这个例子中,我什至比较了 Ticks属性而不是 TotalMilliSeconds , 以(假设)10000 倍的精度获取值 - 如果您比较 TotalMilleseconds相反,您甚至有可能在现代 PC 上获得结果 0 .
Measure-Command内部使用 StopWatch ,而后者又使用 kernel32!QueryPerformanceCounter API,它提供了更精确的线性间隔测量源,因为它不受挂钟抖动和同步的影响 - 这正是您在使用 [StopWatch] 时从未看到这种差异的原因用于外部测量

关于multithreading - 如何保证对象在 Powershell 中实例化的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com