计算程序运行时间
在.net2.0中提供了Stopwatch类,简单例子
using System.Diagnostics;
private Stopwatch stw = new Stopwatch();
private void Form1_Load(object sender, EventArgs e)
{
stw.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("真的要退出?", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
stw.Stop();
MessageBox.Show("程序共运行时间:" + stw.Elapsed.Seconds.ToString() + "秒");
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private Stopwatch stw = new Stopwatch();
private void Form1_Load(object sender, EventArgs e)
{
stw.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("真的要退出?", "退出", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
stw.Stop();
MessageBox.Show("程序共运行时间:" + stw.Elapsed.Seconds.ToString() + "秒");
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
在.net1.1中,需要自己写
using System;
namespace StopWatchTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
StopWatch sw = new StopWatch();
sw.start();
for (long i = 0 ; i < 100000000 ; i++)
{
}
Console.WriteLine(sw.elapsed());
Console.Read();
}
}
class StopWatch
{
private int mintStart;
public void start()
{
mintStart = Environment.TickCount;
}
public long elapsed()
{
return Environment.TickCount - mintStart;
}
}
}
namespace StopWatchTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
StopWatch sw = new StopWatch();
sw.start();
for (long i = 0 ; i < 100000000 ; i++)
{
}
Console.WriteLine(sw.elapsed());
Console.Read();
}
}
class StopWatch
{
private int mintStart;
public void start()
{
mintStart = Environment.TickCount;
}
public long elapsed()
{
return Environment.TickCount - mintStart;
}
}
}