So im writing script in Powershell for assignment and im suposed to replace words in string using 1,2,4 and 8 threads. Im using Start-Job and Wait-Job for threading. In this code i used just a short string but I will be doing this with 5000 word string 10 000 and 20 000 word string. Problem is that when im using 1 thread it runs in ~700ms and more threads I use longer time I get, for example when using 8 threads I get ~1800ms. I guess theres something wrong with my threading but Im complete amateur so I dont know what.
$inputString = "crush, deal, story, clap, early, pagan, fan, avian"
$substringToReplace = "crush"
$replacementSubstring = "red"
# number of jobs
$numJobs = 1
# spliting string to substrings for jobs
$words = $inputString -split " "
$numWordsPerSubstring = [Math]::round($words.Length / $numJobs)
$substrings = @()
for ($i = 0; $i -lt $numJobs; $i++) {
$startIndex = $i * $numWordsPerSubstring
$endIndex = [Math]::Min(($startIndex + $numWordsPerSubstring - 1), ($words.Length - 1))
$substrings += ($words[$startIndex..$endIndex] -join " ") + " "
}
# scriptblock for jobs
$scriptBlock = {
param($substring, $substringToReplace, $replacementSubstring)
$substring -replace $substringToReplace, $replacementSubstring
}
$startTime = [Math]::Round((Get-Date).ToFileTime()/10000)
Write-Host "Start time is $startTime"
# starting each job
$jobs = foreach ($substring in $substrings) {
#Write-Host "Job starte with substring $substring"
Start-Job -ScriptBlock $scriptBlock -ArgumentList $substring, $substringToReplace, $replacementSubstring
}
# waiting for jobs to finnish
$outputString = ""
foreach ($job in $jobs) {
#Write-Host "Job $job ended"
$outputString += Wait-Job $job | Receive-Job
}
$endTime = [Math]::Round((Get-Date).ToFileTime()/10000)
Write-Host "End time is $endTime"
Write-Host "It took $($endTime - $startTime) milliseconds"
Maybe it just takes more time to synchronize more threads Im not sure like i said im complete amateur in Powershell.