[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
using System;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace TestTryCatch
{
class Program
{
static void Main(string[] args)
{
WriteLog("主线程", "程序启动");
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
ArrayList list3 = new ArrayList();
for (int i = 0; i < 10; i++)
{
WriteLog("程序测试", "第[" + i + "]次测试");
Thread.Sleep(1000);
list1.Add(NoTry());
Thread.Sleep(1000);
list2.Add(HaveTry());
Thread.Sleep(1000);
list3.Add(HaveException());
}
long sum1 = 0, sum2 = 0, sum3 = 0;
string str1 = "", str2 = "", str3 = "";
for (int i = 0; i < 10; i++)
{
sum1 += (long)list1;
sum2 += (long)list2;
sum3 += (long)list3;
str1 += list1 + "|";
str2 += list2 + "|";
str3 += list3 + "|";
}
WriteLog("测试结果", "NoTry : " + str1 + sum1/10);
WriteLog("测试结果", "HaveTry : " + str2 + sum2/10);
WriteLog("测试结果", "HaveErr : " + str3 + sum3/10);
WriteLog("主线程", "程序关闭");
Console.Read();
}
private static void WriteLog(string type, string message)
{
Console.WriteLine("[{0}] {1} {2}", DateTime.Now.ToString("yyMMdd HHmmss"), type, message);
}
private static long NoTry()
{
string test = "";
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10000; i++)
{
test += i;
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
private static long HaveTry()
{
string test = "";
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10000; i++)
{
try
{
test += i;
}
catch (Exception err) { }
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
private static long HaveException()
{
string test = "";
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 10000; i++)
{
try
{
test += i;
throw new Exception();
}
catch (Exception err) { }
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
}
}