c纳秒级计时器_纳秒级性能计时器
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
namespace Masuit.Tools.Systems
{
// 納秒級計時器
///
public class HiPerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
private long _startTime;
private long _stopTime;
private readonly long _freq;
///
/// 納秒計數器
///
public HiPerfTimer()
{
_startTime = 0;
_stopTime = 0;
if (QueryPerformanceFrequency(out _freq) == false)
{
// 不支持高性能計數器
throw new Win32Exception();
}
}
///
/// 開始計時器
///
public void Start()
{
// 來讓等待線程工作
Thread.Sleep(0);
QueryPerformanceCounter(out _startTime);
}
///
/// 啟動一個新的計時器
///
///
public static HiPerfTimer StartNew()
{
HiPerfTimer timer = new HiPerfTimer();
timer.Start();
return timer;
}
///
/// 停止計時器
///
public void Stop()
{
QueryPerformanceCounter(out _stopTime);
}
///
/// 時器經過時間(單位:秒)
///
public double Duration => (_stopTime - _startTime) / (double)_freq;
///
/// 執行一個方法并測試執行時間
///
///
///
public static double Execute(Action action)
{
var timer = new HiPerfTimer();
timer.Start();
action();
timer.Stop();
return timer.Duration;
}
}
}
//調用
private void button2_Click(object sender, EventArgs e)
{
HiPerfTimer timer = HiPerfTimer.StartNew();//執行一個待辦事項并測試執行時間
//待辦事項
timer.Stop();
label1.Text="執行耗時" + timer.Duration + "s";// 返回測試時間
double time = HiPerfTimer.Execute(() =>//執行一個方法并測試執行時間
{
//方法
});
label1.Text="執行耗時" + time + "s";//返回測試時間
}
總結
以上是生活随笔為你收集整理的c纳秒级计时器_纳秒级性能计时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 全排列 非递归_全排列(递归与
- 下一篇: 【ES11(2020)】String 扩