LoginSignup
86
76

More than 5 years have passed since last update.

C#メモ 処理時間計測

Last updated at Posted at 2016-11-16

概要

C#でStopwatchクラスを使用した処理時間の計測方法。

コード

使用例
// using System;

// Stopwatchクラス生成
var sw = new System.Diagnostics.Stopwatch();

//-----------------
// 計測開始
sw.Start();

// ★処理A

// 計測停止
sw.Stop();

// 結果表示
Console.WriteLine("■処理Aにかかった時間");
TimeSpan ts = sw.Elapsed;
Console.WriteLine($" {ts}");
Console.WriteLine($" {ts.Hours}時間 {ts.Minutes}{ts.Seconds}{ts.Milliseconds}ミリ秒");
Console.WriteLine($" {sw.ElapsedMilliseconds}ミリ秒");

//-----------------
// 経過時間をリセットしてから計測開始
sw.Restart();

// ★処理B

// 計測停止
sw.Stop();

// 結果表示
Console.WriteLine("■処理Bにかかった時間");
ts = sw.Elapsed;
Console.WriteLine($" {ts}");
Console.WriteLine($" {ts.Hours}時間 {ts.Minutes}{ts.Seconds}{ts.Milliseconds}ミリ秒");
Console.WriteLine($" {sw.ElapsedMilliseconds}ミリ秒");

//-----------------
// 計測再開
sw.Start();

// ★処理C

// 計測停止
sw.Stop();

// 結果表示
Console.WriteLine("■処理BとCにかかった時間");
ts = sw.Elapsed;
Console.WriteLine($" {ts}");
Console.WriteLine($" {ts.Hours}時間 {ts.Minutes}{ts.Seconds}{ts.Milliseconds}ミリ秒");
Console.WriteLine($" {sw.ElapsedMilliseconds}ミリ秒");
実行結果の例
■処理Aにかかった時間
 00:01:03.1235785
 0時間 1分 3秒 123ミリ秒
 63123ミリ秒
■処理Bにかかった時間
 00:00:03.4483858
 0時間 0分 3秒 448ミリ秒
 3448ミリ秒
■処理BとCにかかった時間
 00:00:06.6800882
 0時間 0分 6秒 680ミリ秒
 6680ミリ秒

参考サイト

Stopwatch クラス - MSDN

86
76
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
86
76