Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mklement0/d25dff3f2a24ef9b24b80e647d776467 to your computer and use it in GitHub Desktop.
Save mklement0/d25dff3f2a24ef9b24b80e647d776467 to your computer and use it in GitHub Desktop.
#requires -Version 7
# Download and define function `Time-Command` on demand (will prompt).
# To be safe, inspect the source code at the specified URL first.
if (-not (Get-Command -ErrorAction Ignore Time-Command)) {
$gistUrl = 'https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1'
if ((Read-Host "`n====`n OK to download and define benchmark function ``Time-Command```n from Gist ${gistUrl}?`n=====`n(y/n)?").Trim() -notin 'y', 'yes') { Write-Warning 'Aborted.'; exit 2 }
Invoke-RestMethod $gistUrl | Invoke-Expression 3>$null
if (-not ${function:Time-Command}) { exit 2 }
}
Write-Verbose -Verbose 'Preparing benchmarks...'
# In subfolder ./tf, create 200 subfolders with 10 *.txt files each.
$tf = new-item -force -type directory tf
1..200 | % {
$f = new-item -force -type directory "$tf/$_"
1..10 | % { $null = new-item -force "$f/$_.txt" }
}
Write-Verbose -Verbose 'Running benchmarks...'
$path = $tf.FullName
# Collect the names of all *.txt files in the subfolders.
Time-Command { # foreach statement, no parallelism
$allFileNamesOfInterest =
foreach ($dir in [System.IO.DirectoryInfo]::new($path).GetDirectories()) {
$dir.GetFiles('*.txt').Name
}
},
{ # ForEach-Object, no parallelism
$allFileNamesOfInterest =
[System.IO.DirectoryInfo]::new($path).GetDirectories() | ForEach-Object {
$_.GetFiles('*.txt').Name
}
},
{ # ForEach-Object -Parallel, up to 5 threads by default.
$allFileNamesOfInterest =
[System.IO.DirectoryInfo]::new($path).GetDirectories() | ForEach-Object -Parallel {
$_.GetFiles('*.txt').Name
}
}
Write-Verbose -Verbose 'Cleaning up...'
Remove-Item -LiteralPath $path -Recurse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment