如何计算一段程序逻辑运行时间?

--

 1 class Program
 2     {
 3 
 4         [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
 5         static extern bool QueryPerformanceCounter(ref long count);
 6         [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
 7         static extern bool QueryPerformanceFrequency(ref long count);
 8         [STAThread]
 9         static void Main(string[] args)
10         {
11             Console.WriteLine("开始执行操作
");
12             long count = 0;
13             long count1 = 0;
14             long freq = 0;
15             double result = 0;
16 
17             QueryPerformanceFrequency(ref freq);
18             QueryPerformanceCounter(ref count);
19 
20             #region 程序逻辑执行部分
21             int times = 20;
22             int value = 1;
23             string filePath = "D://123.txt";
24 
25             do
26             {
27                 if (!File.Exists(filePath))
28                 {
29                     var file = File.Create(filePath);
30                     file.Close();
31                     File.WriteAllText(filePath, "1");
32                 }
33                 else
34                 {
35                     value = Convert.ToInt32(File.ReadAllText(filePath));
36                     value++;
37                     File.WriteAllText(filePath, value.ToString());
38                     times--;
39                 }
40                 Console.WriteLine(value);
41             } while (times > 0); 
42             #endregion
43 
44             QueryPerformanceCounter(ref count1);
45             count = count1 - count;
46             result = (double)(count) / (double)freq;
47             Console.WriteLine("结束操作,当前程序耗时: {0} 秒", result);
48             Console.ReadLine();
49         }

      

原文地址:https://www.cnblogs.com/yangda/p/3930034.html