本文介绍了如何测量Java中不受系统时钟变化影响的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想测量Java中的已用时间。但是, System.currentTimeMillis()和(我相信) System.nanoTime()的差异可以通过外部更改进行更改例如某人(或系统)改变系统时钟。I would like to measure elapsed time in a Java. However differences in System.currentTimeMillis() and (I believe) System.nanoTime() can be changed by external changes eg someone (or the system) altering the system clock.使用网络电话不是一种选择,因为它可能非常频繁且需要快速返回。Using network calls is not an option as it's possible very frequent and fast returns are required.这是否有一个共同的解决方案?Is there a common solution for this? 编辑对不起,我应该详细说明原因。它不是为了阻止恶意用户 - 就像客户端发起的空闲登出和常规客户端事件一样。Sorry, I should have elaborated about the reason. It isn't to stop malicious users - it's things like client initiated logout for being idle and routine client events.推荐答案这不是我真的回答你的问题,但是 bug#6458294 意味着哪里可能,Sun的nanoTime()实现将使用真正单调的机制(Linux上的CLOCK_MONOTONIC,Windows上的QueryPerformanceFrequency / QueryPerformanceCounter)。只有当这些不可用时,它才会回退到一个易受系统时钟变化影响的机制。This doesn't really answer your question, but bug #6458294 implies that where possible, Sun's implementation of nanoTime() will use mechanisms which are truly monotonic (CLOCK_MONOTONIC on Linux, QueryPerformanceFrequency/QueryPerformanceCounter on Windows). Only if these are unavailable will it fall back to a mechanism which is susceptible to system clock changes.如果你掌握了硬件的控制权(或至少知识权)重新运行,并确保这些时钟机制可用,你可能很幸运,nanoTime()会很好。If you have control (or at least knowledge) of the hardware you're running on, and can ensure that these clock mechanisms will be available, you might be in luck and nanoTime() will do fine.您可能还想阅读这篇博客文章,更详细地讨论了HotSpot-on-Windows案例。You may also like to read this blog post, which discusses the HotSpot-on-Windows case in more detail. 这篇关于如何测量Java中不受系统时钟变化影响的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-29 05:47