clock()(time.h)函数在C中实现计时器,当在线程中执行时,其运行速度是原来的两倍
我想在C中实现一个计时器,在一个特定的时间之后调用一个函数。我想使用一个线程分别实现计时器。我观察到计时器在线程中实现时的运行速度是在主函数中实现时的两倍 为什么会发生这种情况?我怎样才能修好它 代码1(无线程): 代码2(带定时器)clock()(time.h)函数在C中实现计时器,当在线程中执行时,其运行速度是原来的两倍,c,multithreading,timer,C,Multithreading,Timer,我想在C中实现一个计时器,在一个特定的时间之后调用一个函数。我想使用一个线程分别实现计时器。我观察到计时器在线程中实现时的运行速度是在主函数中实现时的两倍 为什么会发生这种情况?我怎样才能修好它 代码1(无线程): 代码2(带定时器) 要小心,因为两次调用clock测量的时间在不同的平台上测量不同的东西。在Unix和类Unix系统(例如macOS和Linux)上,区别在于进程CPU时间,而在Windows上则基于挂钟 至于你的问题,我想你是在一个Unix或类似Unix的系统上。我认为这仅仅是因为
要小心,因为两次调用
clock
测量的时间在不同的平台上测量不同的东西。在Unix和类Unix系统(例如macOS和Linux)上,区别在于进程CPU时间,而在Windows上则基于挂钟
至于你的问题,我想你是在一个Unix或类似Unix的系统上。我认为这仅仅是因为两个时钟调用之间的差异是一个进程占用的CPU时间,如果您使用线程,那么时间可能会因此而加快(因为线程并行运行)。这与多线程进程使用100%以上CPU时间的原因相同
解决方案是使用其他方法来测量时间,这与CPU时间和线程无关。例如。谢谢。是的,我使用的是Unix系统。
int main (){
unsigned int x_hours=0;
unsigned int x_minutes=0;
unsigned int x_seconds=0;
unsigned int x_milliseconds=0;
unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0, prev_time =10;
clock_t x_startTime,x_countTime;
count_down_time_in_secs=20;
x_startTime=clock(); // start clock
time_left=count_down_time_in_secs-x_seconds;
while (time_left>0)
{
x_countTime=clock(); // update timer difference
x_milliseconds=x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left=count_down_time_in_secs-x_seconds; // subtract to get difference
if(time_left-prev_time != 0)
{
//printf("\nx_countTime = %ju\n",x_countTime);
prev_time = time_left;
//printf( "\nYou have %d seconds left ( %d ) count down timer by TopCoder",time_left,count_down_time_in_secs);
}
}
printf( "\n\n\nTime's out\n\n\n");
return 0;
}
void *timerThread(void *param){
unsigned int x_hours=0;
unsigned int x_minutes=0;
unsigned int x_seconds=0;
unsigned int x_milliseconds=0;
unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0,prev_time =10;
clock_t x_startTime,x_countTime;
count_down_time_in_secs=20;
x_startTime=clock(); // start clock
time_left=count_down_time_in_secs-x_seconds;
while (time_left>0)
{
x_countTime=clock(); // update timer difference
x_milliseconds=x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left=count_down_time_in_secs-x_seconds; // subtract to get difference
if(time_left-prev_time != 0)
{
printf("\nx_countTime = %ju\n",x_countTime);
prev_time = time_left;
printf( "\nYou have %d seconds left ( %d ) count down timer by TopCoder",time_left,count_down_time_in_secs);
}
}
printf( "\n\n\nTime's out\n\n\n");
exit(1);
}
int main()
{
pthread_t *thread_id;
pthread_create(&thread_id, NULL, timerThread, NULL);
while(1);
}