パフォーマンスカウンタ


まあ、素直にパフォーマンスカウンタを使えば良いが、カテゴリ設定がだるかったので。
ホスト指定する際は、権限が必要

static void Main(string[] args)
{
try
{
  if (args == null || args.Length < 1)
  {
    Console.WriteLine("引数1 インスタンス名 (.exe無し) [引数2 待機時間] [引数3 ホスト名]");
    return;
  }

  string prcName = args[0];
  int waitMs = 3000;

  if (args.Length > 1 && int.TryParse(args[1], out waitMs))
  {
    Console.WriteLine("待機時間:{0}秒に設定", waitMs);
  }

  string hostName = null;
  if (args.Length > 2)
  {
    hostName = args[2];
  }

  PerformanceCounterCategory[] cats = null;

  if (string.IsNullOrEmpty(hostName))
    cats = PerformanceCounterCategory.GetCategories();
  else
    cats = PerformanceCounterCategory.GetCategories(hostName);


  PerformanceCounterCategory prcCat = null;
  foreach (var cat in cats)
  {
    Debug.Print(cat.CategoryName);
    if (cat.CategoryName == "Process")
    {
      prcCat = cat;
      break;
    }
  }
  if (prcCat == null)
  {
    Console.WriteLine("Processカテゴリが取得できません。");
    return;
  }

  var thisPrc = Process.GetCurrentProcess();

  PerformanceCounter[] counters = null;

  if (string.IsNullOrEmpty(hostName))
    counters = prcCat.GetCounters(thisPrc.ProcessName);
  else
    counters = prcCat.GetCounters(prcName);

  DateTime dt = DateTime.Now;
  Console.Write(dt.ToShortDateString() + " " + dt.ToLongTimeString());
  foreach (var ct in counters)
  {
    Debug.Print(ct.CounterName);
    Console.Write("," + ct.CounterName);
  }
  Console.Write(Environment.NewLine);

  while (true)
  {
    try
    {
      StringBuilder sb = new StringBuilder();

      dt = DateTime.Now;
      sb.Append(dt.ToShortDateString() + " " + dt.ToLongTimeString());

      foreach (var ct in counters)
      {
        ct.InstanceName = prcName;
        sb.AppendFormat(",{0}", ct.NextValue());
      }
      Console.WriteLine(sb.ToString());

      Thread.Sleep(waitMs);
    }
    catch (Exception ex)
    {
      Debug.Print(ex.Message);
      Debug.Print(ex.StackTrace);
    }//end try

  }//end loop
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
  Console.WriteLine(ex.StackTrace);
}
カテゴリー: 運用, 開発 タグ: パーマリンク