I'm currently working on a self-inspired project to learn powershell, and have been writing a script to generate prime numbers. As it stands, the script works without issue, but my next goal is to increase it's processing speed.
cls
$Primes = @()
$Primes += 3
$TargetNum = 5
$PrimesIndex = 0
$NumOfPrime = 3
while(1)
{
if(($TargetNum / 3) -lt 3)
{
$Primes += $TargetNum
$TargetNum += 2
$NumOfPrime += 1
}
else
{
if($Primes[$PrimesIndex] -le ($TargetNum / ($Primes[$PrimesIndex])))
{
if($TargetNum % $Primes[$PrimesIndex] -eq 0)
{
$PrimesIndex = 0
$TargetNum += 2
}
else
{
$PrimesIndex++
}
}
else
{
$PrimesIndex = 0
$NumOfPrime += 1
$Primes += $TargetNum
$TargetNum += 2
if($TargetNum -gt 100000){write-host $TargetNum ", " $NumOfPrime;break}
}
}
}
If I Execute the statement Measure-command {& ".\primes.ps1"}
it will calculate the first 100,000 primes in ≈ 9.1 seconds (for me anyway), but this is only performing the calculations using a single CPU thread.
I've looked into using start-job
and start-process
commands to implement some sort of multi-threading, but I am failing to understand how they work.
If I moved the prime testing calculation to a function, how would I go about calling that function across all 4 of my logical cores? Perhaps creating a second powershell script that I can pass a value to test, and start-process on that? The above script solves an average of 10,000 primes\sec in the first 10 sec, will powershell even be able to start and stop some worker scripts that quickly?