如何使C程序等待几秒钟?

时间:2020-09-25 12:49:39

标签: c

这是我的代码的两行:

    printf("Correct! \nTime took: %d seconds \n", (now - space));
    if (((now + 5) == time(NULL)) && ((now-space) <= 10))

当然这是行不通的,因为现在不是未来的5秒,但是我的问题是让它等待5秒而不是“哦,现在不是5秒后,所以不,我不会那么做。”有没有办法使这项工作有效?

P.S.有人要求我编写操作系统,即Windows。

3 个答案:

答案 0 :(得分:4)

使用预处理器指令(时间以微秒为单位)的可移植性sleep函数:

#ifdef _WIN32
//  For Windows (32- and 64-bit)
#   include <windows.h>
#   define SLEEP(msecs) Sleep(msecs)
#elif __unix
//  For linux, OSX, and other unixes
#   define _POSIX_C_SOURCE 199309L // or greater
#   include <time.h>
#   define SLEEP(msecs) do {            \
        struct timespec ts;             \
        ts.tv_sec = msecs/1000;         \
        ts.tv_nsec = msecs%1000*1000;   \
        nanosleep(&ts, NULL);           \
        } while (0)
#else
#   error "Unknown system"
#endif

#include <stdio.h>

int main(void)
{
    printf("Hello\n");
    SLEEP(1000); // 1 second
    printf("World\n");
    return 0;
}

我使用Windows 10

然后Sleep(1000)是您要寻找的。

答案 1 :(得分:0)

在C> = 11中,这应该起作用:

#include <threads.h>
#include <stdio.h>
int main(void)
{
    struct timespec few_seconds = { .tv_sec=3 }; //3 seconds
    for(;;){
        int r = thrd_sleep(&few_seconds,&few_seconds);
        if (!r) break; //sleep finished fully
        if (-1!=r) return perror("thrd_sleep"),1; //some weird error?

        //signal interruption: print the remaining time and continue
        printf("rem=%ld.%09ld\n", (long)few_seconds.tv_sec, (long)few_seconds.tv_nsec);
    }
    return 0;
}

如果您的程序不处理任何信号,则不带循环的对thrd_sleep的调用也应该起作用,因为thrd_sleep的调用不应被中断。

答案 2 :(得分:0)

对于微控制器

没有计时器:

void busyWait(unsigned time)
{
  volatile unsigned char dummy=0;
  for(unsigned i=0;i<time;i++)
  {
    //you may need to adjust this value or add more nested loops,
    //depending on the speed of your controller
    for(unsigned j=0;j<10000;j++)
    {
      dummy++;
    }
  }
}

这也可以在普通操作系统上使用,但可能不是最佳策略。

当您要使用计时器时,必须研究控制器的数据表。使用计时器,您的程序可以在等待期间执行其他操作,并且时间可能更精确。

相关问题