时钟函数 usleep 在 C 程序中不能正常工作?
Clock function usleep not working right in c program ?
我想使用 clock_t 类型将我的程序延迟 500 毫秒。例如,我有以下代码:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
clock_t start_t, end_t, total_t,start_2,end_2,total_2;
int i;
start_t = clock();
printf("start_t = %ld\n", start_t);
//do a loop
for(i=0; i< 10000000; i++)
{
}
end_t = clock();
printf("end_t = %ld \n", end_t);
total_t = (double)(end_t - start_t)*1000 / CLOCKS_PER_SEC;
printf("Total1 in msec %ld \n",total_t);
start_2=clock();
printf("start_2 %ld\n ", start_2);
usleep(500000);
end_2=clock();
printf("end_2 %ld\n ", end_2);
total_2=(double)(start_2-end_2)*1000/CLOCKS_PER_SEC;
printf("Total2 in msec %ld\n ", total_2);
return(0);
}
我发现 usleep 将 μsec 的值作为输入。所以我放了 500000。
但我得到:
start_t = 1041
end_t = 50441
Total1 in msec 49
start_2 50446
end_2 50478
Total2 in msec 0
出了什么问题?为什么 total2 =0 ?有什么帮助吗?
事实上,时钟函数记录了这个过程的cpu周期数。当您调用 usleep 函数时,cpu 不会为此过程提供任何时间幻灯片。
所以真正的原因是 clock() 函数。也许你可以找到一些函数来获取系统时间。我认为它会起作用。
找到解决方案。我写了一个延迟函数:
void delay (unsigned int msecs) {
clock_t goal = msecs*CLOCKS_PER_SEC/1000 + clock(); //convert msecs to clock count
while ( goal > clock() ); // Loop until it arrives.
}
我想使用 clock_t 类型将我的程序延迟 500 毫秒。例如,我有以下代码:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
clock_t start_t, end_t, total_t,start_2,end_2,total_2;
int i;
start_t = clock();
printf("start_t = %ld\n", start_t);
//do a loop
for(i=0; i< 10000000; i++)
{
}
end_t = clock();
printf("end_t = %ld \n", end_t);
total_t = (double)(end_t - start_t)*1000 / CLOCKS_PER_SEC;
printf("Total1 in msec %ld \n",total_t);
start_2=clock();
printf("start_2 %ld\n ", start_2);
usleep(500000);
end_2=clock();
printf("end_2 %ld\n ", end_2);
total_2=(double)(start_2-end_2)*1000/CLOCKS_PER_SEC;
printf("Total2 in msec %ld\n ", total_2);
return(0);
}
我发现 usleep 将 μsec 的值作为输入。所以我放了 500000。
但我得到:
start_t = 1041
end_t = 50441
Total1 in msec 49
start_2 50446
end_2 50478
Total2 in msec 0
出了什么问题?为什么 total2 =0 ?有什么帮助吗?
事实上,时钟函数记录了这个过程的cpu周期数。当您调用 usleep 函数时,cpu 不会为此过程提供任何时间幻灯片。 所以真正的原因是 clock() 函数。也许你可以找到一些函数来获取系统时间。我认为它会起作用。
找到解决方案。我写了一个延迟函数:
void delay (unsigned int msecs) {
clock_t goal = msecs*CLOCKS_PER_SEC/1000 + clock(); //convert msecs to clock count
while ( goal > clock() ); // Loop until it arrives.
}