C# 記錄程序運行時間


    最近因需要,做一個記錄程序運行時間的代碼,並計算耗時,以便於測試程序運行速度。

原理:
    被測程序之間定義兩個記錄點。第一個記錄點記錄開始,第二個記錄點記錄結束,得出耗時,保存到文件。這兩個記錄點用標志參數來對應。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace test
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            LogTime(
" Initialize""a");
            InitializeComponent();

            LogTime(
" messB""b");
            MessageBox.Show(
"B");
            LogTime(
" MessB""b");
            MessageBox.Show(
"c");
            LogTime(
"MessC""b");
            LogTime(
"Initialize""a");         
        }
        #region 記錄時間

        
#region 變量定義
        
/// <summary>
        
/// 定義範型保存記錄時間
        
/// </summary>
        static Dictionary<string, DateTime> dytLogTime = new Dictionary<string, DateTime>();
        
/// <summary>
        
/// 保存信息
        
/// </summary>
        static Dictionary<stringstring> dyLogInstruction = new Dictionary<stringstring>();
        
/// <summary>
        
/// 時間變量
        
/// </summary>
        static DateTime dtTime;
        
/// <summary>
        
/// 存放文件的路徑
        
/// </summary>
       static string sPathFile = "";
       
/// <summary>
       
/// 是否冊除過文件
       
/// </summary>
       private static bool IsDeleteOldFile = false;


        
#endregion

        
#region 常量定義
        
/// <summary>
        
/// "Sign:"常量
        
/// </summary>
        private const string csSign = " Sign:";
        
/// <summary>
        
/// "Start"常量
        
/// </summary>
        private const string csStrat = " Start";
        
/// <summary>
        
/// End常量
        
/// </summary>
        private const string csEnd = " End";
        
/// <summary>
        
///Total常量
        
/// </summary>
        private const string csTotal = " Total:";
        
/// <summary>
        
/// "— — —"段落分隔常量
        
/// </summary>
        private const string csLine = "\r\n— — — — — — — — — — — — — — — — \r\n";
        
/// <summary>
        
/// "——"分隔符常量
        
/// </summary>
        private const string csDivide = "——";
        
/// <summary>
        
/// 文件名常量
        
/// </summary>
        private const string csFileName = "ByCooDebugTime.txt";
        
/// <summary>
        
/// 空格常量
        
/// </summary>
        private const string csSpace = " ";
        
/// <summary>
        
/// 日期格式
        
/// </summary>
        private const string csDateFormat = "MM-dd HH:mm:ss ffff";
        
/// <summary>
        
/// ":"冒號常量
        
/// </summary>
        private const string csColon = "";
        
#endregion

        
/// <summary>
        
/// 刪除存在的文件
        /// 第一次記錄時間時,判斷是否文件是否存在,如果存在,將舊的記錄文件刪除。
        /// </summary>
        private static void DeleteOldFile()
        {
            IsDeleteOldFile 
= true;
            GetPathFile();
            
if (System.IO.File.Exists(sPathFile))
            {
                System.IO.File.Delete(sPathFile);
            }
        }

        
/// <summary>
        
/// 記錄時間方法
        
/// 記錄時間並計算出兩個相同標志之間的時間差
        
/// 文件保存在桌面的 當天日期+ByCooDebugTime.txt中
        
/// </summary>
        
/// <param name="asInstruction">說明信息</param>
        
/// <param name="asSign">標志</param>
        private static void LogTime(string asInstruction,string asSign)
        {
            
//記錄文件是否被刪除過
            if (IsDeleteOldFile==false)
            {
                DeleteOldFile();
            }

            
string sRunFile = Application.StartupPath;
            
string sContent = "";  
            
//實例化時間變量
            dtTime=new DateTime();
           
            
//得到當前時間
            dtTime = DateTime.Now;
           
/*
            * 判斷標志是否一致
            * 如果不一致,則表明是新的記錄任務,將標志及時間增加到泛型中保存
            * 如果一致,則表明此為任務的結束,記錄時間並移除泛型中的內容
            * 
            
*/
            
if (!dytLogTime.ContainsKey(asSign))
            {
                
//將開始時間記錄到泛型中
                dytLogTime.Add(asSign, dtTime);
                
//保存說明
                dyLogInstruction.Add(asSign, asInstruction);
                
//記錄開始時間
                sContent = csLine + asSign + csSpace + asInstruction + csStrat + csColon + dtTime.ToString(csDateFormat);
                WriteContentFile(sContent);
            }
            
else
            {
                
//記錄結束時間
                sContent = asSign + csSpace + asInstruction + csEnd + csColon + dtTime.ToString(csDateFormat);
                WriteContentFile(sContent);
                
                
//得到時間差
                string sTotalTime = Convert.ToString(dtTime - dytLogTime[asSign]);

                
//記錄時間差
                sContent = asSign + "(" + dyLogInstruction[asSign] + csStrat + csDivide + asInstruction + csEnd + ")" + csTotal + sTotalTime + csLine;
                WriteContentFile(sContent);
            }

        }

        
/// <summary>
        
/// 將字符寫入文件
        
/// 文件名為 當天日期+ByCooDebugTime.txt
        
/// </summary>
        
/// <param name="asContent"></param>
        private static void WriteContentFile(string asContent)
        {
            StreamWriter mFileWrite;
            
try
            {               
                mFileWrite 
= new StreamWriter(sPathFile, true, Encoding.Default);
                
//將t內容寫入文件
                mFileWrite.WriteLine(asContent);
            }
            
catch (Exception e)
            {
                
throw e;
            }
            mFileWrite.Flush();  
            mFileWrite.Close();
            mFileWrite.Dispose();
        }

        
/// <summary>
        
/// 得到記錄文件存放路徑
        
/// </summary>
        private static void GetPathFile()
        {
            
//存放於桌面
            string folderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            
//存放文件的路徑
            sPathFile = folderPath + "\\" + DateTime.Now.ToString("MM.dd"+ csFileName;
        }

        
#endregion
    }

}

結果:
— — — — — — — — — — — — — — — —
a  Initialize Start: 01-25 11:37:35 1093

— — — — — — — — — — — — — — — —
b  messB Start: 01-25 11:37:35 4687
b  MessB End: 01-25 11:37:37 2343
b( messB Start—— MessB End) Total:00:00:01.7656250
— — — — — — — — — — — — — — — —

b MessC End: 01-25 11:37:38 8906
b( messB Start——MessC End) Total:00:00:03.4218750
— — — — — — — — — — — — — — — —

a Initialize End: 01-25 11:37:38 8906
a( Initialize Start——Initialize End) Total:00:00:03.7812500
— — — — — — — — — — — — — — — —


原文地址:https://www.cnblogs.com/scottckt/p/1052812.html