Đây là câu trả lời của tôi cho đồng hồ bấm giờ sử dụng cả hai mach_absolute_time()
, dựa trên phương pháp tính toán shown here và NSDate
. Thực sự là giống nhau về độ chính xác.
Mach phiên bản
double machGetClockS()
{
static bool init = 0 ;
static mach_timebase_info_data_t tbInfo ;
static double conversionFactor ;
if(!init)
{
init = 1 ;
// get the time base
mach_timebase_info(&tbInfo) ;
conversionFactor = tbInfo.numer/(1e9*tbInfo.denom) ; // ns->s
}
return mach_absolute_time() * conversionFactor ; // seconds
}
double machGetClockDiffS()
{
static double lastTime = 0;
double currentTime = machGetClockS() ;
double diff = currentTime - lastTime ;
lastTime = currentTime ; // update for next call
return diff ; // that's your answer
}
NSTimeInterval phiên bản
double getClockS()
{
return [NSDate timeIntervalSinceReferenceDate] ; // NSTimeInterval is always specified in seconds
}
double getClockDiffS()
{
static double lastTime = 0 ;
double currentTime = getClockS() ;
double diff = currentTime - lastTime ;
lastTime = currentTime ; // update for next call
return diff ; // that's your answer
}
Kết quả:
Lưu ý độ phân giải trên cả hai trong số đó là thực sự tốt.
IOS SIMULATOR, running frame rate counts (in milliseconds (*1000.0))
MACH_ABS_TIME/NSTimeIntervals
58.557001/58.552980
40.558007/40.562987
52.207822/52.200019
33.742197/33.742011
38.498912/38.504004
48.872679/48.868001
45.012602/45.011997
57.858432/57.865977
25.044615/25.038004
IPAD HARDWARE SAMPLINGS:
33.415041/33.416033
33.240167/33.239007
33.357542/33.357978
33.302833/33.302009
33.506750/33.509016
33.582250/33.582985
33.233958/33.232987
33.239042/33.237994
* Nếu bạn nhìn vào lịch sử chỉnh sửa của bài viết này, bạn có thể thấy sự nguy hiểm của việc sử dụng float
vào vị trí của một double
!
Tại sao không chỉ sử dụng 'getrusage()'? Bất cứ điều gì làm việc trong C sẽ làm việc trong Objective-C. –
Bởi vì có một phương pháp Cocoa hoàn hảo tốt để làm điều tương tự. – lucius