作业帮 > 综合 > 作业

运用c语言在linux系统下减少对程序计算时间,急

来源:学生作业帮 编辑:百度作业网作业帮 分类:综合作业 时间:2024/08/06 21:45:47
运用c语言在linux系统下减少对程序计算时间,急
原程序代码如下,没太看懂是如何办到的,还有该方法的移植应该如何处理,
// How to game the OS into not counting your computation:
// Strategy is to do a little work and then sleep until the next tick.
// this works because nanosleep(zero,NULL) sleeps until the next
// accounting tick!So you can do a little work and then
// sleep until *after* the clock has ticked!
#define _POSIX_C_SOURCE 199309
#include
#include
#include
struct timespec zero = {0,0}; // sleep for zero nanoseconds=after next tick!
typedef long cycle_t;
// a sneaky trick to get the number of elapsed cycles of the high-resolution
// clock really quickly by dropping into assembler.Much faster than
// clock_gettime(2) system call.
inline cycle_t get_cycles()
{
cycle_t ret;
asm volatile("rdtsc" :"=A" (ret));
return ret;
}
// calculate the cycles of the high resolution clock per accounting clock tick,
// by waiting through 1000 ticks and dividing.
cycle_t cycles_per_tick()
{
int i;
nanosleep(&zero,NULL); // sync with tick
cycle_t start = get_cycles();
for(i=0 ; i= work ) {// done enough work; wait for tick
nanosleep(&zero,NULL); // avoid bill; wait till after next tick
tick_start = get_cycles(); // start over
}
// do some short work here...
\x05for (i=0; i
运用c语言在linux系统下减少对程序计算时间,急
不知道你代码的目的,不好说你要怎样.
代码也没什么内容,因子的范围也搞不清楚.
另外你需要移植到什么平台?
MingW/Windows应该可以直接运行,多核处理器和SpeedStep可能会引起一些麻烦.
再问: 代码好像是让每1/100秒linux计算程序运行时间时,让程序暂停工作,这样就可以“欺骗”linux,使计算的程序的时间比实际运行时间少,可是具体代码还是不懂……移植那个问题是我没说清楚……我的意思是如果是另外一个不相干的程序同样想达到上述的目的该如何进行啊,谢谢……
再答: 我觉得其实没什么可以移植的,有用的就一行RDTSC,就是一个汇编指令。 RDTSC可以得到一个64位数,如果CPU频率不变,该数值是CPU上电时间*CPU频率。 所以不停地检测该数值就可以知道一个很精确地时间。 nanosleep应该是校准时间的,可以用select代替。 如果时间精度不是很高,Windows里面有GetTickCount,可以替代这些功能。