首页 > 解决方案 > 是否存在返回 int 类型的 time.time() 版本?

问题描述

我的代码需要使用整数 UNIX 时间,但time.time()不适用于我的用例。它返回一个浮点数,并在使用 timeit.timeit 记录时将其转换为 int 或使用 math.floor() 对其进行地板化需要太长时间。

的输出timeit.timeit(lambda : time())约为 0.12 秒,对于我的用例来说已经足够了,但不是 int。
的输出timeit.timeit(lambda : int(time()))大约是 0.25 秒,对于我的用例来说太长了。
timeit.timeit(lambda : math.floor(time()))大约是 0.36 秒,是三者中最差的。

时间非常重要,所以我更喜欢一些内置函数,它将 UNIX 时间返回为 int 而不是 float。

这是我的代码片段:

def main():
    # The value of proceed goes up to 120.
    proceed = 1
    # timeout is some timestamp set at runtime, 2 days from the start of execution.
    while int(time()) <= timeout:
        # tps() uses int(time()), and this is what I want fixed.
        if proceed == tps():
            batchSend(tps())
            proceed += 1
        # These functions also use int(time())
        tocollect = mine()
        collect(tocollect)

标签: pythontimeintepochtimeit

解决方案


原来我没有做作业。timeit.timeit() 的默认number值设置为 100 万,因此实际值比我想象的要小得多。


推荐阅读