LoginSignup
19
12

More than 5 years have passed since last update.

PowerShell で並列処理を試してみた

Last updated at Posted at 2016-06-05

ブログからの転記

並列処理を試す

非同期処理より簡単に導入できそうだったので、PowerShell での並列処理を試してみました

例文での共通部分


3 秒スリープ後、引数で受け取った文字を表示します

function Do-Process()
{
    param(
        [string]
        $text
    )

    $wait = 3
    Start-Sleep -Seconds $wait
    Write-Host "$text, Wait:$wait"
}

同期処理(通常の処理)


5 回 Do-Process を呼び出す(同期処理)

function Test-Sync()
{
    foreach ($i in 1..5) {
        Do-Process "Process ${i}"
    }
}

$time = Measure-Command {
    Test-Sync
}
実行結果
Process 1, Wait:3
Process 2, Wait:3
Process 3, Wait:3
Process 4, Wait:3
Process 5, Wait:3
15029.085

予定通り 15 秒かかっている

並列処理


5 回 Do-Process を呼び出す(並列処理)

Workflow Test-Parallel()
{
    foreach -parallel ($i in 1..5) {
        Do-Process "Process ${i}"
    }
}

$time = Measure-Command {
    Test-Parallel
}
$time.TotalMilliseconds
1回めの実行
Process 5, Wait:3
Process 3, Wait:3
Process 4, Wait:3
Process 2, Wait:3
Process 1, Wait:3
11181.2299

3 秒強の予定だったが 11 秒もかかっている...

2回目の実行
Process 5, Wait:3
Process 4, Wait:3
Process 2, Wait:3
Process 1, Wait:3
Process 3, Wait:3
3754.6529

今度は予定通りの 3 秒強だったが最初は何故時間がかかるんだろう?

参考

19
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12