dongnuoyi8833 2018-04-27 09:52
浏览 65
已采纳

系统睡眠后time.Time.Sub()计算错误

I created a timer application to be run in a terminal window.

I'm witnessing some strange behavior in time.Time.Sub() when I start a terminal timer and put my macOS laptop running it to sleep by closing it.

When I reopen the laptop, suddenly the function appears to not work properly, as tracked by this block of code, which can be seen in this copied output to miscalculate unless I am misunderstanding the time.Time values:

== 615a Timer ==
20m59s

now: 2018-04-27 05:58:20.440440541 -0700 PDT m=+310.234277006
exactLeft: 20m59.142673336s
t.end: 2018-04-27 06:15:00.000129434 -0700 PDT m=+1569.376950342
t.end.Sub(now): 20m59.142673336s

Explicitly, now is set to 5:58 and t.end is set to 6:15, which has a duration of 17m. Yet, t.end.Sub(now) evaluates to 21m, which is a difference of about the time that my laptop was asleep. What is happening here?

  • 写回答

1条回答 默认 最新

  • douzhi9478 2018-04-27 11:15
    关注

    The issue is caused I believe by the difference between wall clock and monotonic clock, both of which may or may not be held inside the Time variables. Different methods on Time variables give different results depending on presence or absence of monotonic clock. I'm not sure of all the ins and outs, and it changed in Go 1.9 I think, but it's documented at the top of the time package and in the godoc.

    I think there may also be some differences dependent on how the specific OS treats monotonic clock. I suspect that the print statement is printing wall clock values but the Sub method is using monotonic.

    Try stripping monotonic clock from one of your Time variables using now = now.Round(0) before calling Sub. That should fix it by forcing it to use wall clock.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)