借用了网友关于win32平台精确定时的方法,将平台调用中的kernel32.dll换成coredll.dll即可。经测试,时间精度到ms以下
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SmartDeviceProject3
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
int sum=1;
HiPerfTimer pt = new HiPerfTimer(); // 创建新的 HiPerfTimer 对象
pt.Start(); // 启动计时器
for (int i = 1; i < 100000; i++)
{
sum *= i;
}
pt.Stop(); // 停止计时器
MessageBox.Show(pt.Duration.ToString());//执行时间按2.35ms,SBC8100开发板
}
class HiPerfTimer
{
[DllImport("coredll.dll")]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("coredll.dll")]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency);
private long startTime, stopTime;
private long freq;
// 构造函数
public HiPerfTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
// 不支持高性能计数器
throw new System.Exception("High performance timer not supported");
}
}
// 开始计时器
public void Start()
{
// 来让等待线程工作
System.Threading.Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
// 停止计时器
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
// 返回计时器经过时间(单位:毫秒)
public double Duration
{
get
{
return ((double)(stopTime - startTime) / (double)freq) * 1000;
}
}
}
}
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SmartDeviceProject3
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
int sum=1;
HiPerfTimer pt = new HiPerfTimer(); // 创建新的 HiPerfTimer 对象
pt.Start(); // 启动计时器
for (int i = 1; i < 100000; i++)
{
sum *= i;
}
pt.Stop(); // 停止计时器
MessageBox.Show(pt.Duration.ToString());//执行时间按2.35ms,SBC8100开发板
}
class HiPerfTimer
{
[DllImport("coredll.dll")]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("coredll.dll")]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency);
private long startTime, stopTime;
private long freq;
// 构造函数
public HiPerfTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
// 不支持高性能计数器
throw new System.Exception("High performance timer not supported");
}
}
// 开始计时器
public void Start()
{
// 来让等待线程工作
System.Threading.Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
// 停止计时器
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
// 返回计时器经过时间(单位:毫秒)
public double Duration
{
get
{
return ((double)(stopTime - startTime) / (double)freq) * 1000;
}
}
}
}