【发布时间】:2014-10-18 00:12:46
【问题描述】:
我的目的是在定义的时间内执行while 循环(例如,本示例为 90 秒)。它不必精确到 90 秒,但 1-2 秒的误差是可以接受的。我确实为此目的使用了clock()`函数:
int main(void){
clock_t start, end;
volatile double elapsed;
start = clock();
int terminate = 1;
while(terminate)
{
end = clock();
elapsed = ((double) (end-start)) / (double) CLOCKS_PER_SEC *1000;
printf("elapsed time:%f\n",elapsed);
if(elapsed >= 90.0)
terminate = 0;
usleep(50000);
}
printf("done..\n");
return 0;
}
当我在笔记本电脑(x86、3.13 内核、gcc 4.8.2)上运行它时,我的秒表测量 72 秒 以完成它。 (在我的笔记本电脑上,elapsed 的秒精度需要 1000)
当我在 ARM 设备(armv5tejl、3.12 内核、gcc 4.6.3)上运行它时,完成代码需要 58 秒。 (我需要在 armv5 上的 elapsed 上使用 100)。
我在室温下运行代码,所以时钟应该是稳定的。我知道内核使线程休眠并且唤醒它们的时间不准确,等等。因此,正如我之前所说,我不希望得到一个完美的时机,但它应该有一定的准确性。
我曾尝试只使用usleep(甚至nanosleep),但分辨率也不好。最后,我提出了获取系统时间(小时、分钟、秒)的底部代码,然后计算经过的时间。它的工作精度很高。
我想知道是否有另一种使用成本更低的解决方案?
typedef struct{
int hour;
int minute;
int second;
} timeInfo;
timeInfo getTimeInfo(void){
timeInfo value2return;
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
value2return.hour = timeinfo->tm_hour;
value2return.minute = timeinfo->tm_min;
value2return.second = timeinfo->tm_sec;
return value2return;
}
int checkElapsedTime(const timeInfo *Start, const timeInfo *Stop, const int Reference){
if(Stop->hour < Start->hour){
printf("1:%d\n", (Stop->hour +24) *3600 + Stop->minute *60 + Stop->second - (Start->hour *3600 +Start->minute * 60 + Start->second));
if( ( (Stop->hour +24) *3600 + Stop->minute *60 + Stop->second - (Start->hour *3600 +Start->minute * 60 + Start->second)) >= Reference )
return 0; //while(0): terminate the loop
else
return 1; //while(1)
}else{
printf("2:%d\n",Stop->hour *3600 + Stop->minute *60 + Stop->second - (Start->hour *3600 +Start->minute * 60 + Start->second));
if( (Stop->hour *3600 + Stop->minute *60 + Stop->second - (Start->hour *3600 +Start->minute * 60 + Start->second)) >= Reference )
return 0;
else
return 1;
}
}
int main(void){
timeInfo stop, start = getTimeInfo();
int terminate = 1;
while(terminate)
{
stop = getTimeInfo();
terminate = checkElapsedTime(&start, &stop, 90);
usleep(5000); //to decrease the CPU load
}
printf("terminated\n");
return 0;
}
最后,我需要在 pthread 中运行它。
【问题讨论】: