c - C中的运行时限制计时器

标签 c timer hour

我想在 C 语言中为我的算法设置一个运行时限制(以小时为单位),以便当它达到限制时,算法停止(例如,在 12 小时)。有没有人对如何执行此操作有任何建议?

最佳答案

您可以使用 time() 来获取开始时间和算法中每次迭代的时间。可以使用difftime()计算差值,当差值超过一定值时终止算法。

假设您的算法是迭代的,下面是一个在 5 秒后终止循环的示例代码。

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

int main(int argc, char **argv)
{
    time_t start_time;
    time_t now_time;

    time(&start_time);
    while (1) {
        /* Your algorithm goes here */

        /* Time check code */
        time(&now_time);

        if (difftime(now_time, start_time) >= 5) {
            break;
        }
    }

    return 0;
}

这是一个非常简单的解决方案,适用于您知道在算法执行期间会经常调用时间检查代码的许多情况。如果您无法找到放置时间检查代码的好位置,以便在算法执行期间经常调用它,则另一种方法是在线程中运行您的算法,并在超过限制时终止它。

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

void *algo(void *arg)
{
    while (1) {
        printf("I AM THE ALGO!!\n");
    }

    return NULL;
}

int main(int argc, char **argv)
{
    time_t start_time;
    time_t now_time;

    pthread_t algo_thread;

    int ret = pthread_create(&algo_thread, NULL, algo, NULL);
    time(&start_time);

    /* Time check loop */
    while (1) {
        time(&now_time);

        if (difftime(now_time, start_time) >= 5) {
            break;
        }
    }

    return 0;
}

关于c - C中的运行时限制计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035848/

相关文章:

c - 二叉搜索树不添加元素

c - 如何使控制台应用程序接收 100,000 个整数的输入

c - 多种类型的归并排序

timer - 如何定期执行 Maya MEL 过程

r - 从时间中提取小时的最快方法(HH :MM)

c - 斐波那契数列C程序错误

java - android中20秒后终止无限循环

objective-c - 在延迟后触发方法而不滥用 [UIView animateWithDuration]?

iphone - 在 UIDatePicker iphone 中选择日期时出现问题

MYSQL 按小时返回 0