麻烦给分析下代码
这是我的毕业设计,是在一本参考书上的。其中有一段VC++代码是用来获取CPU的频率。偶看不懂(基础差),请了解给我解释解释。如果可以的话,请解释得详细些。多谢了!
#define TOLERANCE 1
typedef struct
{
unsigned long in_cycles;
unsigned long ex_ticks;
unsigned long raw_freq;
unsigned long norm_freq;
}FREQ_INFO;
iht _stdcall CpuSpeed()
{ FREQ_INFO cpu_speed;
LARGE INTEGER t0,tl;
unsigned long freq =0;
unsigned long freq2 =0;
unsigned long freq3 =0;
unsigned long total;
int tries=0;
unsigned long total_cycles=O, cycles;
unsigned long stamp0, stampl;
unsigned long total_ticks=O, ticks;
LARGE_INTEGER count_freq;
#ifdef WIN32
iht iPriority;
HANDLE hThread = GetCurrentThread();
#endif // WIN32;
memset(&cpu_speed, 0x00, sizeof(cpu_speed));
QueryPerformanceFrequency ( &count_freq );
do {
tries++;
freq3 = freq2;
freq2 = freq;
QueryPerformanceCounter(&t0);
tl.LowPart = t0.LowPart;
tl.HighPart = t0.HighPart;
#ifdef WIN32
iPriority = GetThreadPriority(hThread);
if ( iPriority != THREAD PRIORITY ERROR RETURN )
{
SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL);
}
#endif
while ( (unsigned long) tl.LowPart-(unsigned long) t0.LowPart<50)
{ QueryPerformanceCounter(&tl);
asm {
RDTSC
MOV stamp0, EAX
}
}
t0.nowPart = tl.nowPart;
t0.HighPart = tl.HighPart;
while ((unsigned long) tl.LowPart-(unsigned long)t0.LowPart<1000 )
{ QueryPerformanceCounter(&tl);
asm {
RDTSC
MOV stampl, EAX
}
#ifdef WIN32
// Reset priority
if ( iPriority != THREAD PRIORITY ERROR RETURN )
{
SetThreadPriority(hThread, iPriority);
}
#endif // WIN32
cycles = stampl - stamp0;
ticks = (unsigned long) tl.LowPart - (unsigned long) t0.LowPart;
ticks = ticks * 100000;
ticks = ticks / ( count_freq.LowPart/10 );
total_ticks+=ticks;
total_cycles += cycles;
if ( ticks%count_freq.LowPart > count_freq.LowPart/2 )
ticks++;
freq = cycles/ticks;
if ( cycles%ticks > ticks/2 )
freq++;
total = ( freq + freq2 + freq3 );
}while ( (tries < 3 ) ||
(tries < 20)&&
((abs(3 * freq -total) > 3*TOLERANCE )||
(abs(3 * freq2-total) > 3*TOLERANCE )||
(abs(3 * freq3-total) > 3*TOLERANCE )));
freq3 = total_cycles * 10 ) / total_ticks;
freq2 = total_cycles * 100 ) / total_ticks;
if ( freq2 - (freq3 * 10) >= ROUND THRESHOLD )
freq3++;
cpu_speed.raw_freq = total_cycles / total_ticks;
cpu_speed.norm_freq = cpu_speed.raw_freq;
freq = cpu_speed.raw_freq * 10;
if( (freq3 - freq) >= ROUND THRESHOLD )
cpu_speed.norm_freq++;
cpu_speed.ex_ticks = total_ticks;
cpu_speed.in_cycles = total_cycles;
return (int)cpu_speed.norm_freq;
}
我的这位导师比较BT,给我的题目是:获取系统信息程序的开发。这题目编程容易论文难写,网上的资料都是些代码,文字材料几乎没有,我都快要想破头了。不知道大家有什么建议呢?
问题点数:0、回复次数:4Top
1 楼idAnts(此广告位招租)回复于 2005-06-01 16:32:04 得分 0
最关键的是用了这条指令RDTSC,然后算出了cpu的频率,当然还有一些相关的工作,提升线程权限,保证线程运行时间。
RDTSC汇编指令可以得到 CPU 内部定时器的值, 每经过一个 CPU 周期, 这个定时器就加一。
如果在一段时间内数得 CPU 的周期数, CPU工作频率 = 周期数 / 时间
上面的程序是循环多次计算出来的,比较准确。
Top
2 楼Dream_Seeker()回复于 2005-06-01 21:53:58 得分 0
感谢楼上大大的讲解,不过我还是希望有人可以比较详细地解释下
早知道设置100分了。。。Top
3 楼wut55()回复于 2005-06-02 00:04:11 得分 0
这段代码的主要意思是把运行的程序优先级设高一点,然后有用一些函数和指令获得cpu的指令周期
,从而得到主频等。Top
4 楼sten(近视进士)回复于 2005-06-02 00:16:13 得分 0
studyingTop




