[System.Runtime.InteropServices.DllImport("Kernel32.dll")] static extern bool QueryPerformanceCounter(ref long count); [System.Runtime.InteropServices.DllImport("Kernel32.dll")] static extern bool QueryPerformanceFrequency(ref long count); long count = 0; long count1 = 0; long freq = 0; double result = 0;
var bt = new System.Diagnostics.Stopwatch(); bt.Start(); //执行你的方法 bt.Stop(); Console.WriteLine(bt.ElapsedMilliseconds); 定义: public class Stopwatch { private long elapsed; public static readonly long Frequency; public static readonly bool IsHighResolution; public static long GetTimestamp(); public void Reset(); public void Start(); public static Stopwatch StartNew(); public void Stop(); public TimeSpan Elapsed { get; } public long ElapsedMilliseconds { get; } public long ElapsedTicks { get; } public bool IsRunning { get; } }
连词去DateTime.Now然后相减,这个方法用来统计方法执行时间误差巨大。
Stopwatch stw = new Stopwatch(); stw.Start(); 你的方法 stw.Stop();stw.ElapsedMilliseconds就该方法之行的时间
static extern bool QueryPerformanceCounter(ref long count); [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
static extern bool QueryPerformanceFrequency(ref long count); long count = 0;
long count1 = 0;
long freq = 0;
double result = 0;
QueryPerformanceFrequency(ref freq);
QueryPerformanceCounter(ref count);
执行方法地方
QueryPerformanceCounter(ref count1);
count = count1 - count;
result = (double)(count) / (double)freq;
bt.Start();
//执行你的方法
bt.Stop();
Console.WriteLine(bt.ElapsedMilliseconds);
定义:
public class Stopwatch
{
private long elapsed;
public static readonly long Frequency;
public static readonly bool IsHighResolution; public static long GetTimestamp();
public void Reset();
public void Start();
public static Stopwatch StartNew();
public void Stop(); public TimeSpan Elapsed { get; }
public long ElapsedMilliseconds { get; }
public long ElapsedTicks { get; }
public bool IsRunning { get; }
}
stw.Start();
你的方法
stw.Stop();stw.ElapsedMilliseconds就该方法之行的时间