【问题标题】:Adding two epoch millseconds in C++在 C++ 中添加两个纪元毫秒
【发布时间】:2013-06-22 02:47:14
【问题描述】:

我的目标是确定一件物品的有效期到它被收购(购买)和出售的时间。每个物品都有一个 TTL 值。

我正在做以下事情:

time_t currentSellingTime;
long currentSystemTime = time(&currentSellingTime); // this gives me epoch millisec of now()

long TTL = <some_value>L;
long BuyingTime = <some_value> // this is also in epoch millsec


if(currentSystemTime >  TTL+BuyingTime))
{
//throw exception 
// item is expired
} 

我的问题是如何将两个纪元毫秒相加并将其与 C++ 中的另一个纪元毫秒进行比较

【问题讨论】:

  • 您可能不想添加它们。这并不意味着什么。拿走差价。
  • @PeterWood 他正在向时间戳添加(或打算添加)一个 TTL(生存时间),因此这可能是未来几年的安全操作,但他的程序 imo 还有其他问题
  • 另外,添加它们可能会导致整数溢出。整数大约可以存储大约 68 年。目前我们距纪元已有 43 年,因此将它们加在一起将得到 86,相当于 18 年(模 68)。

标签: c++ epoch


【解决方案1】:

对于time() works如何可能存在一些误解:

  1. time() 给出的纪元时间以秒表示,而不是毫秒
  2. time 返回当前时间值,并且可以选择在作为其唯一参数的变量中设置当前时间。这意味着

    long currentSystemTime = time(&currentSellingTime);

会将currentSystemTimecurrentSellingTime 都设置为当前时间,这可能不是您打算做的……您可能应该这样做

long currentSystemTime = time(NULL);

time(&currentSellingTime);

但是您使用的“双重形式”非常可疑。为了完整起见,MS Help reference for time()

【讨论】:

  • 谢谢!我做了那个改变。但是对于我的输入集,它进入了不正确的 if 循环。输入:TTL = 1000000,currentSystemTime-1372155260,currentBuyingTime-1372155245。在这个输入中,它不应该进入 if 循环,但它是。
  • 双重形式确实有效,但我同意这不是正确的做法。我已经更正了。
  • @TopCoder 当然它“有效”,但使用 1 次调用来设置两个变量看起来有点奇怪,可能表明存在逻辑缺陷......另外,在你的评论中你正在使用 currentBuyingTime 和在代码示例BuyingTime 中。最后,if 不是循环...
【解决方案2】:

您想使用另一个函数,如前所述,time() 返回秒数。试试:

#include <time.h>


long current_time() {
    struct timespec t;
    clock_gettime(CLOCK_REALTIME, &t);

    return t.tv.sec * 1000l + t.tv_nsec / 1000000l;
}

您的代码应该可以工作。这种方法也与 POSIX 兼容。示例用法:

const long TTL = 100;
long start_time = current_time();

while (!(current_time() > start_time + TTL))
{
    // do the stuff that can expire
}

注意:我知道while 循环中的条件可以用不同的方式构造,但这种方式更像是“直到没有过期”。

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2020-01-11
    • 2012-02-19
    • 2013-01-27
    • 1970-01-01
    • 2018-08-06
    • 2015-07-07
    • 2013-11-11
    • 1970-01-01
    相关资源
    最近更新 更多