1 用Timer 2 用2个Environment.TickCount相减 3 用性能计数器监视时钟,不过写得不完善,这个实例好像很敏感,如果判断是否>0.4会计数一下子跳过, 不判断出来的值是0.XXXXX的 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; using System.Threading;namespace WindowsApplication46 { public partial class Form1 : Form { PerformanceCounter PC = null; float Start = 0; delegate bool TimeElapsed(); public Form1() { InitializeComponent(); PC = new PerformanceCounter("Thread", "Elapsed Time", "System/1"); new Thread(new ThreadStart(RunTime)).Start(); } void RunTime() { while (!(bool)this.Invoke(new TimeElapsed(DoTimeElapsed))) ; } bool DoTimeElapsed() { if (Start == 0) Start = PC.NextValue(); this.Text = (PC.NextValue() - Start).ToString(); return false; } } }
加上系统要处理各种中断,线程们并不能预测它们什么时候能得到运行时间。如果你一定要准确定时(比如某些实时工控系统),Windows并不是合适的平台。
2 用2个Environment.TickCount相减
3 用性能计数器监视时钟,不过写得不完善,这个实例好像很敏感,如果判断是否>0.4会计数一下子跳过,
不判断出来的值是0.XXXXX的
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;
using System.Threading;namespace WindowsApplication46
{
public partial class Form1 : Form
{
PerformanceCounter PC = null;
float Start = 0;
delegate bool TimeElapsed(); public Form1()
{
InitializeComponent();
PC = new PerformanceCounter("Thread", "Elapsed Time", "System/1");
new Thread(new ThreadStart(RunTime)).Start();
} void RunTime()
{
while (!(bool)this.Invoke(new TimeElapsed(DoTimeElapsed)))
;
} bool DoTimeElapsed()
{
if (Start == 0)
Start = PC.NextValue();
this.Text = (PC.NextValue() - Start).ToString();
return false;
}
}
}