使用类似于curl的Invoke-WebRequest测量响应时间



>我有一个curl命令,该命令通过在调用服务中的每个操作来破坏它来响应时间。

curl -w "@sample.txt" -o /dev/null someservice-call

我想使用PowerShell的内置Invoke-WebRequest调用以类似的方式测量响应时间。到目前为止,我能够使用Measure-Command获得总响应时间。有人可以帮我吗?

curl中使用的sample.txt内容:

time_namelookup: %{time_namelookup}               time_connect: %{time_connect}            time_appconnect: %{time_appconnect}           time_pretransfer: %{time_pretransfer}              time_redirect: %{time_redirect}         time_starttransfer: %{time_starttransfer}                            ----------          time_total: %{time_total}

以毫秒为单位的时间:

$url = "google.com"
(Measure-Command -Expression { $site = Invoke-WebRequest -Uri $url -UseBasicParsing }).Milliseconds

这似乎没有任何明显的开销:

$StartTime = $(get-date)
Invoke-WebRequest -Uri "google.com" -UseBasicParsing
Write-Output ("{0}" -f ($(get-date)-$StartTime))

正如其他解决方案指出的那样,仅使用Powershell时存在性能问题。

最有效的解决方案可能是编写一些内置度量的 c#。但是,如果事先没有正确编译它,当需要编译 C# 时,加载时间将急剧增加。

但还有另一种方式。

由于可以在 powershell 中使用几乎所有的 dotnet 构造,因此只需在 powershell 本身中编写相同的请求和度量逻辑即可。 我写了一个小方法,应该可以解决问题:

function Measure-PostRequest {
param(
[string] $Url,
[byte[]] $Bytes,
[switch] $Block
)
$content = [Net.Http.ByteArrayContent]::new($bytes);
$client = [Net.Http.HttpClient]::new();
$stopwatch = [Diagnostics.Stopwatch]::new()
$result = $null;
if ($block) {
# will block and thus not allow ctrl+c to kill the process
$stopwatch.Start()
$result = $client.PostAsync($url, $content).GetAwaiter().GetResult()
$stopwatch.Stop()
} else {
$stopwatch.Start()
$task = $client.PostAsync($url, $content)
while (-not $task.AsyncWaitHandle.WaitOne(200)) { }
$result = $task.GetAwaiter().GetResult()
$stopwatch.Stop()
}
[PSCustomObject]@{
Response = $result
Milliseconds = $stopwatch.ElapsedMilliseconds
}
}

最新更新