.NET代码树执行时间计时器

有很多时候我们需要对代码不同段计算一个执行时间,并希望通过节点树的方式表达现每段代码的执行时长。在.Net下似乎找不到这样一个功能类,所以花了一些时间实现这样一个代码运行计时器。首先看一下简单的需求。

功能代码 

JoinTable table = Order.employeeID.InnerJoin(Employee.employeeID)
    .InnerJoin(Order.customerID, Customer.customerID)
    .Select(Order.orderID.At(), Customer.companyName, Employee.firstName, Employee.lastName);
IList<OrderView> orders = new Expression().List<OrderView>(table);

以上代码是简单地构建一个关联查询表,然后根据这个关联表执行一个简单的订单查询。

加入计时跟踪

现在需要针对以上代码添加一个执行时间跟踪,主要包括总体执行时间,构建查询表的时间和查询的时间。那只需要添加以下代码即可达到跟踪效果。

            TimeWatch.________________________________________________________("list order");
            TimeWatch.________________________________________________________("create table");
            JoinTable table = Order.employeeID.InnerJoin(Employee.employeeID)
    .InnerJoin(Order.customerID, Customer.customerID)
    .Select(Order.orderID.At(), Customer.companyName, Employee.firstName, Employee.lastName);
            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________("List");
            IList<OrderView> orders = new Expression().List<OrderView>(table);
            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________();

计时结果

TimeWatch.Report(o => { Console.WriteLine(o.ToString()); });
通过以上代码就可以把每段执行时间通过树的方式展现出来。

取消和启用跟踪

由于添加了相关跟踪代码,所以使用上就会让人担心这些代码添加了会不会影响代码的总体性能,计时器在实现这些方法的过程中添加了Conditional特性,所以当发布代码的时候把DEBUG的编译符不选上那相关的跟踪代码都不会被编译;因此在编写这些跟踪的时候完全是不用担心对发布的代码产生影响。

更完整的结果

如果下层的组件添加了相关代码,那只要在编译的时候启用DEBUG编译符,那更深层次执行时间树会表现出来。

下载:IKende.com.core.rar

原文地址:https://www.cnblogs.com/smark/p/3412087.html