概述
#include <windows.h>
#include <stdio.h>
/*
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
};
struct {
DWORD LowPart;
LONG HighPart;
} u;
LONGLONG QuadPart;
} LARGE_INTEGER, *PLARGE_INTEGER;
*/
void DelayUs(__int64 Us)
{
LARGE_INTEGER CurrTicks, TicksCount;
QueryPerformanceFrequency(&TicksCount);
QueryPerformanceCounter(&CurrTicks);
TicksCount.QuadPart = TicksCount.QuadPart * Us / 1000000ll;
TicksCount.QuadPart += CurrTicks.QuadPart;
while(CurrTicks.QuadPart<TicksCount.QuadPart)
QueryPerformanceCounter(&CurrTicks);
}
__int64 __rdtsc()
{
#if 1
__int64 val;
__asm__ ("rdtsc" : "=A" (val));
return val;
#else
__int32 lo, hi;
__asm__ __volatile__
(
"rdtsc" : "=a"(lo), "=d"(hi)
);
return (__int64)((lo) | (hi) << 32);
#endif
}
int CPU_Frequency(void) //CPU MHz
{
LARGE_INTEGER CurrTicks, TicksCount;
__int64 iStartCounter, iStopCounter;
/*
DWORD dwOldProcessP = GetPriorityClass(GetCurrentProcess());
DWORD dwOldThreadP = GetThreadPriority(GetCurrentThread());
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
*/
QueryPerformanceFrequency(&TicksCount);
QueryPerformanceCounter(&CurrTicks);
TicksCount.QuadPart /= 16;
TicksCount.QuadPart += CurrTicks.QuadPart;
/*
__asm__ ("rdtsc");
__asm__ ("mov DWORD PTR iStartCounter, EAX");
__asm__ ("mov DWORD PTR (iStartCounter+4), EDX");
*/
iStartCounter = __rdtsc();
while(CurrTicks.QuadPart<TicksCount.QuadPart)
QueryPerformanceCounter(&CurrTicks);
/*
__asm__ ("rdtsc");
__asm__ ("mov DWORD PTR iStopCounter, EAX");
__asm__ ("mov DWORD PTR (iStopCounter + 4), EDX");
*/
iStopCounter = __rdtsc();
/*
SetThreadPriority(GetCurrentThread(), dwOldThreadP);
SetPriorityClass(GetCurrentProcess(), dwOldProcessP);
*/
return (int)(((double)iStopCounter-(double)iStartCounter)/(double)62500);
}
int main()
{
DWORD dwOldProcessP = GetPriorityClass(GetCurrentProcess());
DWORD dwOldThreadP = GetThreadPriority(GetCurrentThread());
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
int s = CPU_Frequency();
printf("cpu: %d Mhzn", s);
__int64 k = __rdtsc();
printf("%ldn", (unsigned long long)k);
__int64 iStartCounter, iStopCounter;
int i;
for (i = 0; i < 10; i++) {
iStartCounter = __rdtsc();
DelayUs(50);
//Sleep(10);
iStopCounter = __rdtsc();
printf("%dn", (iStopCounter - iStartCounter) / s);
}
printf("ok!n");
SetThreadPriority(GetCurrentThread(), dwOldThreadP);
SetPriorityClass(GetCurrentProcess(), dwOldProcessP);
return 0;
}
最后
以上就是满意煎饼为你收集整理的实现高精度定时器的全部内容,希望文章能够帮你解决实现高精度定时器所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复