Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

powershell/bench.ps1

SHA-256 (LF line endings, as in the source ZIP): 2e94358ea1c22a34919a0826870b7e3abdcc34ac94a8cccc295ed5c0c55c53a0 · MIT license (the benchmark suite only)

<#
.SYNOPSIS
  competitive-bench-v1 - the PowerShell baseline, "optimized streaming" (runs unchanged on Windows PowerShell 5.1
  and PowerShell 7).

.DESCRIPTION
  bench.ps1 -Scenario <id> -InputPath <log> [-Repeat N] [-Output <file>]

  Prints one JSON line: the result, the time of each in-process repetition (runsMs), the process's CPU time and peak
  working set. How it reads: a .NET StreamReader (1 MB buffer) line by line - never the whole file, no pipeline per
  line; ordinal String.Contains / IndexOf for text, String.Split for W3C fields (positions from the #Fields header),
  a generic Dictionary for counting, [double]::Parse with the invariant culture for numbers. Single-threaded. No C#
  is compiled in (that would be the C# baseline). It reads the input and writes only -Output.
#>
param(
    [Parameter(Mandatory = $true)] [string]$Scenario,
    [Parameter(Mandatory = $true)] [string]$InputPath,
    [int]$Repeat = 1,
    [string]$Output = ''
)
$ErrorActionPreference = 'Stop'
$invariant = [System.Globalization.CultureInfo]::InvariantCulture

function Open-Reader([string]$path) {
    $stream = New-Object System.IO.FileStream($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read,
        ([System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete), 1048576, [System.IO.FileOptions]::SequentialScan)
    return New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::ASCII, $false, 1048576)
}

function Get-FieldIndex([string]$header) {
    $index = @{}
    $names = $header.Substring(9).Split(' ')
    for ($i = 0; $i -lt $names.Length; $i++) { $index[$names[$i]] = $i }
    return $index
}

function Invoke-LiteralError([string]$path) {
    $n = 0
    $reader = Open-Reader $path
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Contains('ERROR')) { $n++ }
        }
    } finally { $reader.Dispose() }
    return @{ count = $n }
}

function Invoke-ElapsedGe1000([string]$path) {
    $n = 0
    $reader = Open-Reader $path
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            $at = $line.IndexOf('elapsed: ', [System.StringComparison]::Ordinal)
            if ($at -lt 0) { continue }
            $end = $line.IndexOf('ms', $at + 9, [System.StringComparison]::Ordinal)
            if ($end -gt $at + 9 -and [double]::Parse($line.Substring($at + 9, $end - $at - 9), $invariant) -ge 1000) { $n++ }
        }
    } finally { $reader.Dispose() }
    return @{ count = $n }
}

function Invoke-Count([string]$path, [string]$field, [int]$min) {
    $n = 0
    $reader = Open-Reader $path
    $col = -1
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Length -eq 0) { continue }
            if ($line[0] -eq '#') {
                if ($line.StartsWith('#Fields: ', [System.StringComparison]::Ordinal)) { $ix = Get-FieldIndex $line; $col = $ix[$field] }
                continue
            }
            $f = $line.Split(' ')
            if ([int]$f[$col] -ge $min) { $n++ }
        }
    } finally { $reader.Dispose() }
    return @{ count = $n }
}

function Invoke-Top([string]$path, [string]$key, [int]$minStatus, [int]$onlyStatus, [bool]$post) {
    $counts = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([System.StringComparer]::Ordinal)
    $matched = 0
    $reader = Open-Reader $path
    $s = -1; $k = -1; $m = -1
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Length -eq 0) { continue }
            if ($line[0] -eq '#') {
                if ($line.StartsWith('#Fields: ', [System.StringComparison]::Ordinal)) {
                    $ix = Get-FieldIndex $line; $s = $ix['sc-status']; $k = $ix[$key]; $m = $ix['cs-method']
                }
                continue
            }
            $f = $line.Split(' ')
            $status = [int]$f[$s]
            if ($onlyStatus -gt 0) { if ($status -ne $onlyStatus) { continue } } elseif ($status -lt $minStatus) { continue }
            if ($post -and $f[$m] -cne 'POST') { continue }
            $matched++
            $v = $f[$k]
            $c = 0
            [void]$counts.TryGetValue($v, [ref]$c)
            $counts[$v] = $c + 1
        }
    } finally { $reader.Dispose() }
    $top = New-Object System.Collections.Generic.List[object]
    foreach ($kv in ($counts.GetEnumerator() | Sort-Object @{ Expression = { $_.Value }; Descending = $true }, @{ Expression = { $_.Key }; Descending = $false } | Select-Object -First 10)) {
        $top.Add(@($kv.Key, $kv.Value))
    }
    return @{ count = $matched; top = $top }
}

function Invoke-PerMinute([string]$path) {
    $counts = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([System.StringComparer]::Ordinal)
    $reader = Open-Reader $path
    $s = -1; $d = -1; $t = -1
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Length -eq 0) { continue }
            if ($line[0] -eq '#') {
                if ($line.StartsWith('#Fields: ', [System.StringComparison]::Ordinal)) {
                    $ix = Get-FieldIndex $line; $s = $ix['sc-status']; $d = $ix['date']; $t = $ix['time']
                }
                continue
            }
            $f = $line.Split(' ')
            if ([int]$f[$s] -lt 500) { continue }
            $minute = $f[$d] + 'T' + $f[$t].Substring(0, 5)
            $c = 0
            [void]$counts.TryGetValue($minute, [ref]$c)
            $counts[$minute] = $c + 1
        }
    } finally { $reader.Dispose() }
    $buckets = New-Object System.Collections.Generic.List[object]
    foreach ($key in ($counts.Keys | Sort-Object -CaseSensitive)) { $buckets.Add(@($key, $counts[$key])) }
    return @{ buckets = $buckets }
}

function Invoke-Records([string]$path, [string]$output, [bool]$projected) {
    if (-not $output) { throw '-Output is required' }
    $n = 0
    $writer = New-Object System.IO.StreamWriter($output, $false, (New-Object System.Text.UTF8Encoding($false)), 65536)
    $writer.NewLine = "`n"
    $reader = Open-Reader $path
    $names = $null; $s = -1; $m = -1
    try {
        while ($null -ne ($line = $reader.ReadLine())) {
            if ($line.Length -eq 0) { continue }
            if ($line[0] -eq '#') {
                if ($line.StartsWith('#Fields: ', [System.StringComparison]::Ordinal)) {
                    $ix = Get-FieldIndex $line; $names = $line.Substring(9).Split(' '); $s = $ix['sc-status']; $m = $ix['cs-method']
                }
                continue
            }
            $f = $line.Split(' ')
            if ([int]$f[$s] -ne 503 -or $f[$m] -cne 'POST') { continue }
            $n++
            if ($projected) {
                $rec = [ordered]@{ time = $f[$ix['date']] + 'T' + $f[$ix['time']] + 'Z'; 'c-ip' = $f[$ix['c-ip']]; 'cs-uri-stem' = $f[$ix['cs-uri-stem']] }
            } else {
                $rec = [ordered]@{}
                for ($i = 0; $i -lt $names.Length; $i++) { $rec[$names[$i]] = $f[$i] }
            }
            $writer.WriteLine(($rec | ConvertTo-Json -Compress))
        }
    } finally { $reader.Dispose(); $writer.Dispose() }
    return @{ count = $n; bytes = (Get-Item $output).Length }
}

function Invoke-Scenario([string]$id) {
    switch ($id) {
        'literal-error' { return Invoke-LiteralError $InputPath }
        'elapsed-ge-1000' { return Invoke-ElapsedGe1000 $InputPath }
        'count-5xx' { return Invoke-Count $InputPath 'sc-status' 500 }
        'count-slow' { return Invoke-Count $InputPath 'time-taken' 1000 }
        'top-ip-5xx' { return Invoke-Top $InputPath 'c-ip' 500 0 $false }
        'top-uri-5xx' { return Invoke-Top $InputPath 'cs-uri-stem' 500 0 $false }
        'top-ip-503-post' { return Invoke-Top $InputPath 'c-ip' 0 503 $true }
        'per-minute-5xx' { return Invoke-PerMinute $InputPath }
        'records-503-post-full' { return Invoke-Records $InputPath $Output $false }
        'records-503-post-projected' { return Invoke-Records $InputPath $Output $true }
        default { throw "unknown scenario $id" }
    }
}

$runs = New-Object System.Collections.Generic.List[double]
$result = $null
for ($r = 0; $r -lt $Repeat; $r++) {
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    $result = Invoke-Scenario $Scenario
    $sw.Stop()
    $runs.Add([math]::Round($sw.Elapsed.TotalMilliseconds, 3))
}
$self = [System.Diagnostics.Process]::GetCurrentProcess()
$report = [ordered]@{
    implementation      = 'powershell'
    runtime             = 'PowerShell ' + $PSVersionTable.PSVersion.ToString() + ' (' + $PSVersionTable.PSEdition + ')'
    scenario            = $Scenario
    result              = $result
    runsMs              = $runs
    cpuMs               = [math]::Round($self.TotalProcessorTime.TotalMilliseconds, 1)
    peakWorkingSetBytes = $self.PeakWorkingSet64
}
[Console]::Out.WriteLine(($report | ConvertTo-Json -Compress -Depth 6))