惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Y
Y Combinator Blog
M
MIT News - Artificial intelligence
The Cloudflare Blog
WordPress大学
WordPress大学
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 司徒正美
小众软件
小众软件
Blog — PlanetScale
Blog — PlanetScale
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
J
Java Code Geeks
云风的 BLOG
云风的 BLOG
C
Check Point Blog
D
DataBreaches.Net
T
The Blog of Author Tim Ferriss
V
V2EX
F
Fortinet All Blogs
B
Blog
大猫的无限游戏
大猫的无限游戏
N
Netflix TechBlog - Medium
B
Blog RSS Feed
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

博客园 - ∈鱼杆

TraceView .NET WAP网站开发系列 ASP.NET RSS开发札记(完结) MonoRail MVC实践应用(完结) HowTo:String.Format新方法 HowTo:C#性能测试扩展函数 Python性能测试工具 Excel分类汇总宏(VBA) Python性能测试工具 MonoRailMVC应用-母板页的Title 面向方面的编程在Cache、Log、Trace方面的运用 MonoRail MVC应用(2)-构建多层结构的应用程序 MonoRail MVC应用(1)-VM/HTML页面 MonoRail MVC实践应用 W3WP进程CPU查看 innerHTML和P标签 [转] 有关敏捷的若干思考 .NET WAP开发及兼容问题 ASP.NET分页控件(AspNetPager分页控件)
HowTo:C#性能测试扩展函数
∈鱼杆 · 2008-12-22 · via 博客园 - ∈鱼杆

看了ark的文章让我想起了些这个。可能没有太多的实际意义,但确是一个不错的思路。
我们平时在使用stopwatch统计时间的时候一般会这样使用。

Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < runs; i++)
{
.......
}
watch.Stop();

这样就可以统计到运行的时间,但用过Python的人都知道,python自备电池。那么其实用扩展函数就可以实现这个类似功能(PS:其实功能还是相差蛮大的,但皮已经画的很像了)。
先演示如何使用(统计A.Run这个方法的使用时间)

class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            Action act = a.Run;
            Console.WriteLine(act.Profile(100));
            Console.Read();
        }
    }
    public class A
    {
        public void Run()
        {
            for (int i =0; i < 100000; i++) ;
        }
    }
}

用扩展方法来实现这个需求,这样就不用重复写stopwatch了

public static class FunctionHelper
    {
        public static string Profile(this Action func, int runs)
        {     Stopwatch watch = Stopwatch.StartNew();   for (int i = 0; i < runs; i++)
            {
                func();
            }
            watch.Stop();   float sec = watch.ElapsedMilliseconds / 1000.0f;
            float freq = runs / sec;     return String.Format("execute runs:{0};sec:{1};freq",
                                runs,  //运行次数 
                                sec,   // 运行时间
                                freq // 平均运行时间
                                );   }   }

有了这个扩展方法,你就可以对某些特定的方法自动调用性能函数了。