【问题标题】:calculate how many days before a unix process time overflows计算unix进程时间溢出前多少天
【发布时间】:2017-01-31 02:51:37
【问题描述】:

我正在研究 Unix 环境中的高级编程示例,并提出了以下问题:

如果进程时间存储为32位有符号整数,系统每秒计数100个tick,多少天后数值会溢出?

void proc_ovf()
{
        int sec = 60;
        int min = 60;
        int hour = 24;
        int tick = 100;
        int epoch_time = (((INT_MAX / (sec * tick)) / min) / hour);
        struct tm * timeinfo;
        time_t epoch_time_as_proc_t = epoch_time;
        timeinfo = localtime(&epoch_time_as_proc_t);
        printf("3] overflow date of proc: %s", asctime(timeinfo));
}

以下解决方案是否合理计算溢出前多少天?

(((INT_MAX / (sec * tick)) / min) / hour)

这个计算得出 248 天。

【问题讨论】:

    标签: c unix


    【解决方案1】:

    248 天看起来不错。

    但您的代码没有。您的变量名称错误。它们应该是:

    int ticks_per_second = 100;
    int seconds_per_minute = 60;
    int minutes_per_hour = 60;
    int hours_per_day = 24;
    
    int ticks = INT_MAX;
    int seconds = ticks / ticks_per_second;
    int minutes = seconds / seconds_per_minute;
    int hours = minutes / minutes_per_hour;
    int days = hours / hours_per_day;
    
    printf("overflow after %d days\n", days);
    

    上面的代码负责提及测量单位。你能看到代码第二部分的每一行中的度量单位抵消得有多好吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-24
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      相关资源
      最近更新 更多