在windows平台上使用 CreateTimerQueueTimer定时器时,需要将精度设置到1-2 ms的时间,但是CreateTimerQueueTimer的执行时间片在15ms左右,后来无意间找到一篇文章
原来是微软故意这么干的,他觉得设置精度到毫秒级别,太耗费资源了,如果是移动设备,频繁唤醒切换线程,电池消耗得很快。于是微软宁肯抛弃强兼容性传统,也坚决让这函数失效。悲催啊!性能问题,你这样搞就很扯淡呀微软!!!!!!
注意:DeleteTimerQueueTimer最后一个参数最好设置为INVALID_HANDLE_VALUE;不然频繁销毁定时器,会造成coredump
DeleteTimerQueueTimer(m_hTimerQueue, m_hTimer, INVALID_HANDLE_VALUE);
实现一个达到微秒级别的延时
#define SECOND_S 1
#define SECOND_MS 1000
#define SECOND_US 1000000
int UsSleep(int us)
{
//储存计数的联合
LARGE_INTEGER fre;
//获取硬件支持的高精度计数器的频率
if (QueryPerformanceFrequency(&fre))
{
LARGE_INTEGER run,priv,curr,res;
run.QuadPart = fre.QuadPart * us / SECOND_MS;//转换为微妙级
//获取高精度计数器数值
QueryPerformanceCounter(&priv);
do
{
QueryPerformanceCounter(&curr);
} while (curr.QuadPart - priv.QuadPart < run.QuadPart);
curr.QuadPart -= priv.QuadPart;
int nres = (curr.QuadPart * SECOND_MS / fre.QuadPart);//实际使用微秒时间
return nres;
}
return -1;//
}
#include<time.h>
void get_time_str(char *local_time_str)
{
time_t timep;
struct tm *p;
time(&timep);
p = gmtime(&timep);
struct timeb tb;
ftime(&tb);
sprintf(local_time_str, "%d-%d-%d %02d:%02d:%02d:%03d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, 8 + p->tm_hour, p->tm_min, p->tm_sec, tb.millitm);
}