LoginSignup
1
0

【PowerShell】処理時間を測定する

Posted at

はじめに

PowerShellで作ったスクリプトのパフォーマンスの尺度として、処理時間の測定方法を調べた結果を記事としてまとめてみました。

学習環境

今回はコマンドプロンプトとVS Codeを使いました。

コマンドプロンプト(DOS)を使う方法

  • PowerShellで処理時間を求める前に、比較対象としてコマンドプロンプトを使う方法をまとめておきます。
  • コマンドプロンプトだとtimeを使って現在の時刻を求めますが、以下のように開始時間と終了時間から自力で処理時間を求めることになります。
processing_time.bat
set start_time=%time%
rem pingをsleepの代わりに利用
Ping -n 3 localhost > null
set end_time=%time%

echo %start_time%
echo %end_time%
実行結果
11:58:14.16
11:58:16.21

PowerShellを使う方法

  • PowerShellではMeasure-Command関数を使って処理時間を求めます。
  • スクリプトブロックを使うことで簡単に処理時間を求めることができますが、「日」「時」「分」「秒」「ミリ秒」のそれぞれの単位での結果が混在していて、これだと見づらいですね...
processing_time.ps1
Measure-Command {
    Start-Sleep -Seconds 3
}
実行結果
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 3
Milliseconds      : 12
Ticks             : 30121641
TotalDays         : 3.48630104166667E-05        
TotalHours        : 0.00083671225
TotalMinutes      : 0.050202735
TotalSeconds      : 3.0121641
TotalMilliseconds : 3012.1641
  • そこで以下のように修正してみると、欲しかった「秒単位の処理時間」だけを求めることができました。
    • コマンドプロンプトのtimeを使うよりも、これなら圧倒的に楽でスッキリ書けますね。
processing_time2.ps1
$prcessing_time = Measure-Command {
    Start-Sleep -Seconds 3
}

Write-Host "$($prcessing_time.Seconds) seconds"
実行結果2
3 seconds

参考URL

1
0
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
1
0