/ src / modules / launcher / Wox.Infrastructure / Stopwatch.cs
Stopwatch.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System;
 6  using System.Collections.Generic;
 7  using System.Reflection;
 8  using System.Threading;
 9  
10  using Wox.Plugin.Logger;
11  
12  namespace Wox.Infrastructure
13  {
14      public static class Stopwatch
15      {
16          private static readonly Dictionary<string, long> Count = new Dictionary<string, long>();
17          private static readonly Lock Locker = new Lock();
18  
19          /// <summary>
20          /// This stopwatch will appear only in Debug mode
21          /// </summary>
22          public static long Debug(string message, Action action)
23          {
24              ArgumentNullException.ThrowIfNull(action);
25  
26              var stopWatch = new System.Diagnostics.Stopwatch();
27              stopWatch.Start();
28              action();
29              stopWatch.Stop();
30              var milliseconds = stopWatch.ElapsedMilliseconds;
31              string info = $"{message} <{milliseconds}ms>";
32              Log.Debug(info, MethodBase.GetCurrentMethod().DeclaringType);
33              return milliseconds;
34          }
35  
36          public static long Normal(string message, Action action)
37          {
38              ArgumentNullException.ThrowIfNull(action);
39  
40              var stopWatch = new System.Diagnostics.Stopwatch();
41              stopWatch.Start();
42              action();
43              stopWatch.Stop();
44              var milliseconds = stopWatch.ElapsedMilliseconds;
45              string info = $"{message} <{milliseconds}ms>";
46              Log.Info(info, MethodBase.GetCurrentMethod().DeclaringType);
47              return milliseconds;
48          }
49  
50          public static void StartCount(string name, Action action)
51          {
52              ArgumentNullException.ThrowIfNull(action);
53  
54              var stopWatch = new System.Diagnostics.Stopwatch();
55              stopWatch.Start();
56              action();
57              stopWatch.Stop();
58              var milliseconds = stopWatch.ElapsedMilliseconds;
59              lock (Locker)
60              {
61                  if (Count.ContainsKey(name))
62                  {
63                      Count[name] += milliseconds;
64                  }
65                  else
66                  {
67                      Count[name] = 0;
68                  }
69              }
70          }
71  
72          public static void EndCount()
73          {
74              foreach (var key in Count.Keys)
75              {
76                  string info = $"{key} already cost {Count[key]}ms";
77                  Log.Debug(info, MethodBase.GetCurrentMethod().DeclaringType);
78              }
79          }
80      }
81  }