【问题标题】:Measure response time using Invoke-WebRequest similar to curl使用类似于 curl 的 Invoke-WebRequest 测量响应时间
【发布时间】:2018-12-14 08:40:45
【问题描述】:

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

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

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

sample.txt 的内容用于curl

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

【问题讨论】:

  • 我认为Invoke-WebRequest 做不到。是什么让你想使用Invoke-WebRequest
  • Invoke-WebRequest 类似于wgetInvoke-RestMethodcurl
  • 您可能必须编写自己的Invoke-RestMethodInvoke-WebRequest 版本来衡量流程中的各个步骤并提供反馈。您可以将进度偏好设置为 ($ProgressPreference = 'Continue'),但这并不是您想要的。
  • @Rock 看到我的答案了吗?

标签: powershell curl response-time


【解决方案1】:

以毫秒为单位的时间:

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

【讨论】:

  • 这可行,但性能不是很好。如果我在上面使用-method head,我会得到大约 40-50 毫秒,但如果我在带有 HEAD 的 Firefox 中做同样的事情,它只有大约 10-15 毫秒。本地网络服务器的类似结果,3-5 毫秒 vs 50-60 毫秒。
  • 同意,短响应时间测试没有意义,某处有巨大的开销!
  • 使用 measure 命令,您将获得一切,包括解析实际命令、创建和设置请求和响应等。它不仅会测量请求时间本身。不幸的是,我不知道实现这一目标的简单方法。
  • 为 necro-bumping 道歉,但这确实对我有很大帮助。我认为您要在此处报告的实际属性是 .TotalMilliseconds (毫秒相对于当前秒)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    正如其他解决方案所指出的,仅使用 poershell 时会出现性能问题。

    最有效的解决方案可能是编写一些内置测量的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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2020-05-17
      • 2019-01-02
      • 1970-01-01
      相关资源
      最近更新 更多