我正在研究 Unix 环境中的高级编程示例,并提出了以下问题:
如果处理时间存储为 32 位有符号整数,并且系统每秒计数 100 个刻度,那么多少天后该值会溢出?
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/(秒 * 刻度))/分钟)/小时)
此计算结果为 248 天。
最佳答案
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);
上面的代码负责提及测量单位。您能看到代码第二部分的每一行中的测量单位抵消得有多好吗?
关于计算 UNIX 进程时间溢出之前还有多少天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942853/