Thread.Sleep和Timer效能比較
阿新 • • 發佈:2019-02-19
今天比較一下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會線上程池中取新的執行緒來執行,存在多次訪問執行緒池的損耗。
測試程式碼:
- class Program
- {
- privatestatic System.Timers.Timer _timer;
- privatestatic volatile int _Max = 100000;
-
privatestatic volatile int _ThreadMax = 100000;
- staticvoid 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();
- }
- staticprivatevoid StartThread()
- {
- Thread s = new Thread(ThreadGo);
- s.Start();
- }
- staticprivatevoid 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();
- }
- staticprivatevoid StartTimer()
- {
- _timer = new System.Timers.Timer();
- _timer.AutoReset = true;
- _timer.Interval = 10;
- _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
- _timer.Start();
- }
- staticvoid _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();
- }
- }
- }