问题描述:
睡眠线程耗时测试:
DateTime startTime = DateTime.Now;
Thread.Sleep(1);
DateTime endTime = DateTime.Now;
TimeSpan tp = endTime - startTime;
txtMsg.AppendText("睡眠线程耗时测试:"+ (tp.TotalMilliSeconds-1)+ “ms” + Enviroment.NewLine);
运行发现,耗时14.6212ms。初步判断,开启Thread.Sleep()方法有一个耗时,这个耗时为14.6212ms。
为了进一步验证这一判断。
写了一个控制台程序,程序中写了一个循环,然后控制每次循环执行的持续时间,分别为2ms,3ms,4ms,5ms.
按照如下代码执行,发现平均耗时均为15.6212ms.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace testhuahan
{
class Program
{
static void Main(string[] args)
{
int count=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("执行中......");
DateTime starttime = DateTime.Now;
for (int i = 0; i < count; i++)
{
Thread.Sleep(1);
}
DateTime endtime = DateTime.Now;
TimeSpan tp = endtime - starttime;
Console.WriteLine("开始时间:"+starttime);
Console.WriteLine("结束时间:"+endtime);
Console.WriteLine("总计耗时:"+tp.TotalMilliseconds);
Console.WriteLine("总计耗时:"+tp.TotalMilliseconds);
Console.WriteLine("平均耗时:" + tp.TotalMilliseconds/count);
Console.ReadKey();
}
}
}
解决方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
namespace testhuahan
{
class Program
{
//--------------------------------------
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
public static extern uint MM_BeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
public static extern uint MM_EndPeriod(uint uMilliseconds);
//---------------------------------------
static void Main(string[] args)
{
MM_BeginPeriod(1);//-----------------------
int count=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("执行中......");
DateTime starttime = DateTime.Now;
for (int i = 0; i < count; i++)
{
Thread.Sleep(1);
}
DateTime endtime = DateTime.Now;
TimeSpan tp = endtime - starttime;
Console.WriteLine("开始时间:"+starttime);
Console.WriteLine("结束时间:"+endtime);
Console.WriteLine("总计耗时:"+tp.TotalMilliseconds);
Console.WriteLine("总计耗时:"+tp.TotalMilliseconds);
Console.WriteLine("平均耗时:" + tp.TotalMilliseconds/count);
Console.ReadKey();
MM_EndPeriod(1);//--------------------------
}
}
}
运行结果:
这样,开启Thread.Sleep()方法的耗时变为0.833234ms。
需要设置循环的时间间隔为2ms,3ms,4ms,5ms等要求时,便不会再出现十几毫秒,相差太大的情况了。
以下是参考的“Thread.Sleep精度问题”的博客:
Thread.Sleep的精度默认在15ms左右,如果需要类似 Thread.Sleep(1)的精细控制,需要调用特定的平台API实现
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
public static extern uint MM_BeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
public static extern uint MM_EndPeriod(uint uMilliseconds);
MM_BeginPeriod(1);
Thread.Sleep(1);
MM_EndPeriod(1);