Stopwatch + C#打印日志方法

时间:2022-03-16 20:32:03

打印一个接口、方法的运行时间在程序中是很容易遇到的一件事情;现在,我就分享一个我在工作中使用的临时打印日志的方法和结合 Stopwatch 打印测量某个时间间隔的运行时间的方法。

Stopwatch 实例可以很好的测量一个时间间隔的运行时间;以下例子是比较常用到的:

引用命名空间: using System.Diagnostics;

Stopwatch//Stopwatch 实例

Start;//开始或继续测量某个时间间隔的运行时间

Elapsed;//获取当前实例测量得出的总运行时间(以时分秒为单位)

ElapsedMilliseconds;//获取当前实例测量得出的总运行时间(以毫秒为单位)

Reset;//停止时间间隔测量,并将运行时间重置为零

Restart;//停止时间间隔测量,并将运行时间重置为零,然后开始测量运行时间

打印日志方法,目录也可以自己指定:

         public static void WriteError(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory;//获取基目录
path = System.IO.Path.GetDirectoryName(path) + " \\ErrorLogs";//设置输出日志输出目录
try
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
string fileName = System.IO.Path.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true);//文件流创建写数据流
sw.WriteLine(DateTime.Now.ToString("HH:mm:ss:fff") + " -------------------");
sw.WriteLine(message);
sw.WriteLine();
sw.Close();//关闭写数据流
}
catch
{
}
}

结合Stopwatch 使用打印测量某个时间间隔的运行时间的方法

          var s = new Stopwatch();
//需要测试运行时间的的代码
WriteError(s.ElapsedMilliseconds.ToString() + " GetNewUpdateFileList");//打印运行时间
 s.Reset();

注:方法为小七在工作中用到的方法,如果转载,请注明出处;

有不对或遗漏的地方,欢迎指出;

欢迎评论;