1. [代码].NET 2.0
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;}}
2. [代码].NET 1.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;}}}