在c中实现时间延迟

发布于 2024-09-27 06:12:13 字数 121 浏览 3 评论 0 原文

我不知道如何确切地表达这个搜索..所以我没有找到任何东西..:S

我需要在C中实现时间延迟

。例如我想做一些事情,然后等待说 1 分钟,然后继续做事。

这有道理吗?有人可以帮我吗?

I don't know exactly how to word a search for this.. so I haven't had any luck finding anything.. :S

I need to implement a time delay in C.

for example I want to do some stuff, then wait say 1 minute, then continue on doing stuff.

Did that make sense? Can anyone help me out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

天暗了我发光 2024-10-04 06:12:14

尝试sleep(int number_of_seconds)

Try sleep(int number_of_seconds)

前事休说 2024-10-04 06:12:14

sleep(int) 可以起到很好的延迟作用。一分钟:

//Doing some stuff...
sleep(60); //Freeze for A minute
//Continue doing stuff...

sleep(int) works as a good delay. For a minute:

//Doing some stuff...
sleep(60); //Freeze for A minute
//Continue doing stuff...
攒一口袋星星 2024-10-04 06:12:14

你可以简单地调用delay()函数。因此,如果您想将进程延迟 3 秒,请调用delay(3000)...

you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...

伪装你 2024-10-04 06:12:14

如果您确定要等待并且永远不会被打断,请在 POSIX 中使用 sleep 或在 Windows 中使用 Sleep。在 POSIX 中,睡眠需要以秒为单位的时间,因此如果您希望时间更短,可以使用像 usleep() 这样的变体,它使用微秒。 Windows 中的睡眠需要几毫秒,您很少需要比这更细的粒度。

您可能希望等待一段时间,但又希望允许中断,也许是在紧急情况下。睡眠可以被信号中断,但在这种情况下有更好的方法。

因此,我实际上在实践中发现您所做的就是等待具有超时的事件或条件变量。

在 Windows 中,您的调用是 WaitForSingleObject。在 POSIX 中,它是 pthread_cond_timedwait

在 Windows 中,您还可以使用 WaitForSingleObjectEx,然后您可以通过调用 QueueUserAPC 实际上“中断”线程并执行任何排队任务。 WaitForSingleObject(Ex) 将返回一个代码来确定它退出的原因,因此当它返回“TIMEDOUT”状态时您就会知道它确实超时了。当您希望它终止时,您可以设置它正在等待的事件。

使用pthread_cond_timedwait,您可以用信号广播条件变量。 (如果多个线程正在等待同一个线程,则需要广播来唤醒所有线程)。每次循环时都应该检查条件。您的线程可以获取当前时间并查看它是否已经过去,或者可以查看是否满足某些条件来确定要做什么。如果您有某种队列,您可以检查一下。 (您的线程将自动锁定一个互斥锁,用于等待条件变量,因此当它检查条件时,它可以单独访问它)。

If you are certain you want to wait and never get interrupted then use sleep in POSIX or Sleep in Windows. In POSIX sleep takes time in seconds so if you want the time to be shorter there are varieties like usleep() which uses microseconds. Sleep in Windows takes milliseconds, it is rare you need finer granularity than that.

It may be that you wish to wait a period of time but want to allow interrupts, maybe in the case of an emergency. sleep can be interrupted by signals but there is a better way of doing it in this case.

Therefore I actually found in practice what you do is wait for an event or a condition variable with a timeout.

In Windows your call is WaitForSingleObject. In POSIX it is pthread_cond_timedwait.

In Windows you can also use WaitForSingleObjectEx and then you can actually "interrupt" your thread with any queued task by calling QueueUserAPC. WaitForSingleObject(Ex) will return a code determining why it exited, so you will know when it returns a "TIMEDOUT" status that it did indeed timeout. You set the Event it is waiting for when you want it to terminate.

With pthread_cond_timedwait you can signal broadcast the condition variable. (If several threads are waiting on the same one, you will need to broadcast to wake them all up). Each time it loops it should check the condition. Your thread can get the current time and see if it has passed or it can look to see if some condition has been met to determine what to do. If you have some kind of queue you can check it. (Your thread will automatically have a mutex locked that it used to wait on the condition variable, so when it checks the condition it has sole access to it).

薆情海 2024-10-04 06:12:14

// 提供延迟x毫秒的ANSI C方法

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void delayMillis(unsigned long ms) {
    clock_t start_ticks = clock();
    unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
    while (clock()-start_ticks < ms*millis_ticks) {
    }
}    

/* 
 * Example output:
 * 
 * CLOCKS_PER_SEC:[1000000]
 * 
 * Test Delay of 800 ms....
 * 
 * start[2054], end[802058], 
 * elapsedSec:[0.802058]
 */
int testDelayMillis() {

    printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
    clock_t start_t, end_t;
    start_t = clock();
    printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
    delayMillis(800); 
    end_t = clock();
    double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
    printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);

}

int main() {    
    testDelayMillis();
}

// Provides ANSI C method of delaying x milliseconds

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void delayMillis(unsigned long ms) {
    clock_t start_ticks = clock();
    unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
    while (clock()-start_ticks < ms*millis_ticks) {
    }
}    

/* 
 * Example output:
 * 
 * CLOCKS_PER_SEC:[1000000]
 * 
 * Test Delay of 800 ms....
 * 
 * start[2054], end[802058], 
 * elapsedSec:[0.802058]
 */
int testDelayMillis() {

    printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
    clock_t start_t, end_t;
    start_t = clock();
    printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
    delayMillis(800); 
    end_t = clock();
    double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
    printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);

}

int main() {    
    testDelayMillis();
}
几度春秋 2024-10-04 06:12:14

C11 有一个专门用于此目的的函数:

#include <threads.h>
#include <time.h>
#include <stdio.h>

void sleep(time_t seconds) {
    struct timespec time;
    time.tv_sec = seconds;
    time.tv_nsec = 0;
    while (thrd_sleep(&time, &time)) {}
}

int main() {
    puts("Sleeping for 5 seconds...");
    sleep(5);
    puts("Done!");
    return 0;
}

请注意,该函数仅从 glibc 2.28 开始可用。

C11 has a function specifically for this:

#include <threads.h>
#include <time.h>
#include <stdio.h>

void sleep(time_t seconds) {
    struct timespec time;
    time.tv_sec = seconds;
    time.tv_nsec = 0;
    while (thrd_sleep(&time, &time)) {}
}

int main() {
    puts("Sleeping for 5 seconds...");
    sleep(5);
    puts("Done!");
    return 0;
}

Note that this is only available starting in glibc 2.28.

遥远的她 2024-10-04 06:12:14

用于 gcc 中的 C 使用。
#include ;

然后使用 Sleep(); /// Sleep() 大写 S。而不是 sleep() 大写 s 。

//Sleep(1000) 是 1 秒 /// 也许。

clang 支持 sleep(),sleep(1) 是 1 秒的时间延迟/等待。

for C use in gcc.
#include <windows.h>

then use Sleep(); /// Sleep() with capital S. not sleep() with s .

//Sleep(1000) is 1 sec /// maybe.

clang supports sleep(), sleep(1) is for 1 sec time delay/wait.

第几種人 2024-10-04 06:12:14

对于 Linux 操作系统上的短暂延迟(例如几微秒),您可以使用“usleep”:

// C Program to perform short delays
#include <unistd.h>
#include <stdio.h>

int main(){
    printf("Hello!\n");
    usleep(1000000); // For a 1-second delay
    printf("Bye!\n);
    return 0;

For short delays (say, some microseconds) on Linux OS, you can use "usleep":

// C Program to perform short delays
#include <unistd.h>
#include <stdio.h>

int main(){
    printf("Hello!\n");
    usleep(1000000); // For a 1-second delay
    printf("Bye!\n);
    return 0;
王权女流氓 2024-10-04 06:12:14
system("timeout /t 60"); // waits 60s. this is only for windows vista,7,8
system("ping -n 60 127.0.0.1 >nul"); // waits 60s. for all windows
system("timeout /t 60"); // waits 60s. this is only for windows vista,7,8
system("ping -n 60 127.0.0.1 >nul"); // waits 60s. for all windows
酒儿 2024-10-04 06:12:14

写下这段代码:

void delay(int x)
{   int i=0,j=0;
    for(i=0;i<x;i++){for(j=0;j<200000;j++){}}
}

int main()
{
    int i,num;

    while(1) {

    delay(500);

    printf("Host name");
    printf("\n");}

}

Write this code :

void delay(int x)
{   int i=0,j=0;
    for(i=0;i<x;i++){for(j=0;j<200000;j++){}}
}

int main()
{
    int i,num;

    while(1) {

    delay(500);

    printf("Host name");
    printf("\n");}

}
微暖i 2024-10-04 06:12:13

在标准 C (C99) 中,您可以使用 time() 来执行此操作,例如:

#include <time.h>
:
void waitFor (unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

顺便说一句,这假设 time() 返回 1 秒分辨率值。我认为标准没有强制要求,因此您可能需要进行调整。


为了澄清,这是我所知道的使用 ISO C99 执行此操作的唯一方法(问题仅用“C”标记,这通常意味着便携式解决方案是可取的,尽管,当然,仍然可能会给出特定于供应商的解决方案)。

无论如何,如果您所在的平台提供了更有效的方式,请使用它。正如一些评论所指出的,像这样的紧密循环可能会存在与 CPU 相关的特定问题使用情况和电池寿命。

任何像样的时间切片操作系统都能够降低连续使用其完整时间片的任务的动态优先级,但电池电量可能会出现更多问题。

然而,C 没有指定有关托管环境中操作系统详细信息的任何内容,并且此答案仅适用于 ISO C 和 ISO C(因此不使用 sleepselect< /code>、Win32 API 调用或类似的东西)。

请记住 POSIX sleep 可以被信号打断。如果您要走这条路,您需要执行以下操作:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}

In standard C (C99), you can use time() to do this, something like:

#include <time.h>
:
void waitFor (unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.


In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).

By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.

Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.

However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).

And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}
北风几吹夏 2024-10-04 06:12:13

以下是在大多数桌面系统上执行此操作的方法:

#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif

void wait( int seconds )
{   // Pretty crossplatform, both ALL POSIX compliant systems AND Windows
    #ifdef _WIN32
        Sleep( 1000 * seconds );
    #else
        sleep( seconds );
    #endif
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

以下是在没有计时器的微型计算机/处理器上执行此操作的方法:

int wait_loop0 = 10000;
int wait_loop1 = 6000;

// for microprocessor without timer, if it has a timer refer to vendor documentation and use it instead.
void
wait( int seconds )
{   // this function needs to be finetuned for the specific microprocessor
    int i, j, k;
    for(i = 0; i < seconds; i++)
    {
        for(j = 0; j < wait_loop0; j++)
        {
            for(k = 0; k < wait_loop1; k++)
            {   // waste function, volatile makes sure it is not being optimized out by compiler
                int volatile t = 120 * j * i + k;
                t = t + 5;
            }
        }
    }
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

等待循环变量必须进行微调,这些变量对于我的计算机来说工作得非常接近,但是频率范围这使得现代桌面系统变得非常不精确;所以不要在那里使用,除非你是裸露的金属并且不做这样的事情。

Here is how you can do it on most desktop systems:

#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif

void wait( int seconds )
{   // Pretty crossplatform, both ALL POSIX compliant systems AND Windows
    #ifdef _WIN32
        Sleep( 1000 * seconds );
    #else
        sleep( seconds );
    #endif
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

Here is how you can do it on a microcomputer / processor w/o timer:

int wait_loop0 = 10000;
int wait_loop1 = 6000;

// for microprocessor without timer, if it has a timer refer to vendor documentation and use it instead.
void
wait( int seconds )
{   // this function needs to be finetuned for the specific microprocessor
    int i, j, k;
    for(i = 0; i < seconds; i++)
    {
        for(j = 0; j < wait_loop0; j++)
        {
            for(k = 0; k < wait_loop1; k++)
            {   // waste function, volatile makes sure it is not being optimized out by compiler
                int volatile t = 120 * j * i + k;
                t = t + 5;
            }
        }
    }
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

The waitloop variables must be fine tuned, those did work pretty close for my computer, but the frequency scale thing makes it very imprecise for a modern desktop system; So don't use there unless you're bare to the metal and not doing such stuff.

瞎闹 2024-10-04 06:12:13

尽管许多实现都有 time 函数返回当前时间时间以为单位,不能保证每个实现都会这样做(例如,有些可能返回毫秒而不是 >)。因此,更便携的解决方案是使用 difftime 函数。

C 标准保证 difftime 返回两个 time_t 值之间的时间差(以为单位)。因此,我们可以编写一个可移植的时间延迟函数,它将在C 标准的所有兼容实现上运行。

#include <time.h>

void delay(double dly){
    /* save start time */
    const time_t start = time(NULL);

    time_t current;
    do{
        /* get current time */
        time(¤t);

        /* break loop when the requested number of seconds have elapsed */
    }while(difftime(current, start) < dly);
}

关于 timedifftime 函数的一个警告是,C 标准从未指定粒度。大多数实现的粒度为一秒。虽然这对于持续几秒的延迟来说是可以的,但对于持续一秒的延迟,我们的延迟函数可能会等待太长时间。

有一个可移植的标准 C 替代方案:clock 函数。

clock 函数返回自仅与程序调用相关的实现定义时代开始以来程序使用的处理器时间的最佳近似值。要确定以秒为单位的时间,应将 clock 函数返回的值除以宏 CLOCKS_PER_SEC.


clock 函数解决方案与我们的 time 函数解决方案非常相似:

#include <time.h>

void delay(double dly){
    /* save start clock tick */
    const clock_t start = clock();

    clock_t current;
    do{
        /* get current clock tick */
        current = clock();

        /* break loop when the requested number of seconds have elapsed */
    }while((double)(current-start)/CLOCKS_PER_SEC < dly);
}

在这种情况下有一个类似于 time 的警告difftime:时钟函数的粒度留给实现。例如,具有 32 位 clock_t 值且分辨率以微秒为单位的机器可能最终会在 2147 秒后包装 clock 返回的值(约36分钟)。

因此,考虑使用延迟函数的 timedifftime 实现来实现持续至少一秒的延迟,以及 clock< /code> 延迟持续一秒的实现。

最后要注意的是:clock 返回处理器时间而不是日历时间时钟可能与实际经过的时间不符(例如,如果进程休眠)。

Although many implementations have the time function return the current time in seconds, there is no guarantee that every implementation will do so (e.g. some may return milliseconds rather than seconds). As such, a more portable solution is to use the difftime function.

difftime is guaranteed by the C standard to return the difference in time in seconds between two time_t values. As such we can write a portable time delay function which will run on all compliant implementations of the C standard.

#include <time.h>

void delay(double dly){
    /* save start time */
    const time_t start = time(NULL);

    time_t current;
    do{
        /* get current time */
        time(¤t);

        /* break loop when the requested number of seconds have elapsed */
    }while(difftime(current, start) < dly);
}

One caveat with the time and difftime functions is that the C standard never specifies a granularity. Most implementations have a granularity of one second. While this is all right for delays lasting several seconds, our delay function may wait too long for delays lasting under one second.

There is a portable standard C alternative: the clock function.

The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC.

The clock function solution is quite similar to our time function solution:

#include <time.h>

void delay(double dly){
    /* save start clock tick */
    const clock_t start = clock();

    clock_t current;
    do{
        /* get current clock tick */
        current = clock();

        /* break loop when the requested number of seconds have elapsed */
    }while((double)(current-start)/CLOCKS_PER_SEC < dly);
}

There is a caveat in this case similar to that of time and difftime: the granularity of the clock function is left to the implementation. For example, machines with 32-bit values for clock_t with a resolution in microseconds may end up wrapping the value returned by clock after 2147 seconds (about 36 minutes).

As such, consider using the time and difftime implementation of the delay function for delays lasting at least one second, and the clock implementation for delays lasting under one second.

A final word of caution: clock returns processor time rather than calendar time; clock may not correspond with the actual elapsed time (e.g. if the process sleeps).

傲娇萝莉攻 2024-10-04 06:12:13

对于长达一分钟的延迟,sleep() 是一个不错的选择。

如果有一天,您想要在小于一秒的延迟上暂停,您可能需要考虑超时的 poll()

两者都是 POSIX。

For delays as large as one minute, sleep() is a nice choice.

If someday, you want to pause on delays smaller than one second, you may want to consider poll() with a timeout.

Both are POSIX.

烛影斜 2024-10-04 06:12:13

C11 之前的 C 标准库中没有 sleep() 函数,但 POSIX 确实提供了一些选项。

POSIX 函数 sleep() (unistd.h) 需要一个 unsigned int 参数,表示所需睡眠的秒数。尽管这不是标准库函数,但它被广泛使用,并且即使在使用 --std=c11 等更严格的设置进行编译时,glibc 似乎也支持它。

POSIX 函数 nanosleep() ( time.h) 将两个指向 timespec 结构的指针作为参数,并提供对睡眠持续时间的更精细的控制。第一个参数指定延迟持续时间。如果第二个参数不是空指针,则它保存调用被信号处理程序中断时剩余的时间。

使用 nanosleep() 函数的程序可能需要包含 功能测试宏以便编译。当我使用典型的编译器调用 gcc -std=c11 -Wall -Wextra -Wpedantic 时,如果没有功能测试宏,以下代码示例将无法在我的 Linux 系统上进行编译。

POSIX 曾经有一个 usleep() 函数(unistd. h) 使用 useconds_t 参数来指定睡眠持续时间(以微秒为单位)。当与严格的编译器设置一起使用时,该函数还需要一个功能测试宏。唉,usleep() 已随 POSIX.1-2001 废弃,不应再使用。建议现在使用 nanosleep() 而不是 usleep()

#define _POSIX_C_SOURCE  199309L     // feature test macro for nanosleep()

#include <stdio.h>
#include <unistd.h>    // for sleep()
#include <time.h>      // for nanosleep()

int main(void)
{
    // use unsigned sleep(unsigned seconds)
    puts("Wait 5 sec...");
    sleep(5);

    // use int nanosleep(const struct timespec *req, struct timespec *rem);
    puts("Wait 2.5 sec...");
    struct timespec ts = { .tv_sec = 2,          // seconds to wait
                           .tv_nsec = 5e8 };     // additional nanoseconds
    nanosleep(&ts, NULL);
    puts("Bye");

    return 0;
}

附录:

C11 确实有标头 threads.h 提供 thrd_sleep(),其工作方式与nanosleep()相同。直到 2018 年,随着 threads.h >glibc 2.28。一般来说,很难找到支持 threads.h 的实现(Clang 很长一段时间都不支持它,但我不确定那里的当前状况)。您必须小心使用此选项。

There are no sleep() functions in the pre-C11 C Standard Library, but POSIX does provide a few options.

The POSIX function sleep() (unistd.h) takes an unsigned int argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like --std=c11.

The POSIX function nanosleep() (time.h) takes two pointers to timespec structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.

Programs that use the nanosleep() function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation of gcc -std=c11 -Wall -Wextra -Wpedantic.

POSIX once had a usleep() function (unistd.h) that took a useconds_t argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas, usleep() was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended that nanosleep() be used now instead of usleep().

#define _POSIX_C_SOURCE  199309L     // feature test macro for nanosleep()

#include <stdio.h>
#include <unistd.h>    // for sleep()
#include <time.h>      // for nanosleep()

int main(void)
{
    // use unsigned sleep(unsigned seconds)
    puts("Wait 5 sec...");
    sleep(5);

    // use int nanosleep(const struct timespec *req, struct timespec *rem);
    puts("Wait 2.5 sec...");
    struct timespec ts = { .tv_sec = 2,          // seconds to wait
                           .tv_nsec = 5e8 };     // additional nanoseconds
    nanosleep(&ts, NULL);
    puts("Bye");

    return 0;
}

Addendum:

C11 does have the header threads.h providing thrd_sleep(), which works identically to nanosleep(). GCC did not support threads.h until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support for threads.h (Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文