2008年2月25日 星期一

利用stopwatch 測試程式效率 && try.catch 效率測試

最近在寫一隻Windows Form 的程式,這隻程式最主要的功能是計算公司一年來所有的工作天數,休假天數,及調休天數,這隻程式其實沒什麼難度,但完成時我發現怎麼程式執行效率很差,於是就需要來找出問題的地方在那我上網查詢如何測試程式效率的方法查到使用stopwatch,
命名空間:System.Diagnostics


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{ //try catch 測試 未發生例外
Stopwatch stopwatch;
String num = "5";
int result;
stopwatch = Stopwatch.StartNew();
for (int i = 1; i <= 1000; i++)
{
try
{
result = int.Parse(num);
}
catch
{
result = 0;
}
}
stopwatch.Stop();
textBox1.Text = stopwatch.ElapsedTicks.ToString();
}

private void button2_Click(object sender, EventArgs e)
{
//int.TryParse 測試 未發生例外
Stopwatch stopwatch;
String num = "5";
int result;
int nn;
stopwatch = Stopwatch.StartNew();
for (int i = 1; i <= 1000; i++)
{
if (!int.TryParse(num, out nn))
result = 0;
}
stopwatch.Stop();
textBox1.Text = stopwatch.ElapsedTicks.ToString();
}

private void button3_Click(object sender, EventArgs e)
{
////try catch 測試 發生例外
Stopwatch stopwatch;
String num = "5a";
int result;
stopwatch = Stopwatch.StartNew();
for (int i = 1; i <= 1000; i++)
{
try
{
result = int.Parse(num);
}
catch
{
result = 0;
}
}
stopwatch.Stop();
textBox1.Text = stopwatch.ElapsedTicks.ToString();
}

private void button4_Click(object sender, EventArgs e)
{
Stopwatch stopwatch;
String num = "5a";
int result;
int nn;
stopwatch = Stopwatch.StartNew();
for (int i = 1; i <= 1000; i++)
{
if (!int.TryParse(num, out nn))
result = 0;
}
stopwatch.Stop();
textBox1.Text = stopwatch.ElapsedTicks.ToString();
}
}
}

執行結果:


  上圖可以發現,平常使用try..catch對效率是差不多的,但是一出現例外狀況,差異就很大了,也就是能把預期會出現的意外狀況盡量用IF判斷掉,不然就像我這次寫程式一樣,因為效率不好,搞到後來大幅的改寫,那才是真的叫累人~

沒有留言: