获得当前系统时间毫秒的最佳方法是什么?
当前回答
CFAbsoluteTimeGetCurrent ()
Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.
其他回答
It may be useful to know about CodeTimestamps, which provide a wrapper around mach-based timing functions. This gives you nanosecond-resolution timing data - 1000000x more precise than milliseconds. Yes, a million times more precise. (The prefixes are milli, micro, nano, each 1000x more precise than the last.) Even if you don't need CodeTimestamps, check out the code (it's open source) to see how they use mach to get the timing data. This would be useful when you need more precision and want a faster method call than the NSDate approach.
http://eng.pulse.me/line-by-line-speed-analysis-for-ios-apps/
到目前为止,我发现gettimeofday在iOS (iPad)上是一个很好的解决方案,当你想执行一些间隔评估(比如帧速率,渲染帧的计时……):
#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
如果你不想包含Quartz框架,[NSDate timeintervalsincerely eferencedate]是另一个选项。它返回一个double,表示秒数。
如果你正在考虑使用这个相对定时(例如游戏或动画),我宁愿使用CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
哪一种是推荐的方式;NSDate从网络的同步时钟中提取,并且在与网络重新同步时偶尔会打嗝。
它返回当前的绝对时间,以秒为单位。
如果你只想要小数部分(通常在同步动画时使用),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)
推荐文章
- 更改UITextField和UITextView光标/插入符颜色
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- 如何设置回退按钮文本在Swift
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 如何比较两个nsdate:哪个是最近的?
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序
- 删除/重置核心数据中的所有条目?
- setNeedsLayout vs. setNeedsUpdateConstraints和layoutIfNeeded vs. updateConstraintsIfNeeded
- 如何删除列表中的最后一项?
- 不区分大小写的比较
- 我怎么能得到一个uiimage的高度和宽度?
- 如何计算两次约会之间的间隔时间?