Thread.Sleep和Timer性能比较

在一些需要隔时触发的场景中,如javascript中的setInterval函数,在.Net中,你用什么?
是System.Timer.Timer?
or
while(true)
{
     Thread.Sleep(1000);

}

今天比较一下Timer和Sleep.

结果:Thread.sleep,问天下谁于争峰。

空间:
Type         work set      virtual bytes    page file bytes  Thread Count Handle 
Timer        8.990.720     114.978.816      11.444.224       4       115
Thread.Sleep 6.590464      104.296.448      7.143.424        3        95

Thread.Sleep全胜

时间:
Type         start Time    Interval times   finish time
Timer        11:53:37:416  10ms 100000      12:19:37:555
Thread.Sleep 11:53:37:432  10ms 100000      12:19:36:713

Timer和Thread.Sleep打个平手,但Thread.sleep还是要强那么一点

分析:
Thread.sleep直接调用内核的指令,所在线程挂起,CPU执行队列的重排序。
Timer每次Elapsed会在线程池中取新的线程来执行,存在多次访问线程池的损耗。

测试代码: 

view plaincopy to clipboardprint?
class Program  
{  
    private static System.Timers.Timer _timer;  
    private static volatile int _Max = 100000;  
    private static volatile int _ThreadMax = 100000;  
      
    static void Main(string[] args)  
    {  
        Console.WriteLine(System.DateTime.Now.ToString() + System.DateTime.Now.Millisecond.ToString());  
        StartTimer();  
        Console.WriteLine(System.DateTime.Now.ToString() + System.DateTime.Now.Millisecond.ToString());  
        StartThread();  
        Console.ReadLine();  
    }  
    static private void StartThread()  
    {  
        Thread s = new Thread(ThreadGo);  
        s.Start();  
    }  
    static private void ThreadGo()  
    {  
        while (true)  
        {  
            Thread.Sleep(10);  
            _ThreadMax--;  
            if (_ThreadMax < 0) break;  
        }  
        Console.WriteLine("ThreadGo" + System.DateTime.Now.ToString() + System.DateTime.Now.Millisecond.ToString());  
        Thread.CurrentThread.Abort();  
    }  
    static private void StartTimer()  
    {  
        _timer = new System.Timers.Timer();  
        _timer.AutoReset = true;  
        _timer.Interval = 10;  
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);  
        _timer.Start();  
    }  
 
    static void _timer_Elapsed(object sender, ElapsedEventArgs e)  
    {  
        _Max--;  
        if(_Max<0)  
        {  
            Console.WriteLine("_timer_Elapsed" + System.DateTime.Now.ToString() + System.DateTime.Now.Millisecond.ToString());  
            _timer.Stop();  
            _timer.Dispose();  
        }  
    }  

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gisfarmer/archive/2009/03/13/3986277.aspx

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值