是否有一种方法可以确定一个方法需要执行多少时间(以毫秒为单位)?
当前回答
mach_absolute_time()有一个方便的包装器——它是来自CoreAnimation框架的CACurrentMediaTime()函数。
与NSDate或CFAbsoluteTimeGetCurrent()偏移量不同, mach_absolute_time()和CACurrentMediaTime()基于 主机内部时钟,精确,单原子测量,且不受影响 外部时间参考的更改,例如由时间引起的更改 区域、夏令时或闰秒。
ObjC
#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// Do your stuff here
CFTimeInterval endTime = CACurrentMediaTime();
NSLog(@"Total Runtime: %g s", endTime - startTime);
斯威夫特
import QuartzCore
let startTime = CACurrentMediaTime()
// Do your stuff here
let endTime = CACurrentMediaTime()
print("Total Runtime: \(endTime - startTime) s")
其他回答
许多答案很奇怪,并没有真正以毫秒为单位给出结果(而是以秒或其他单位):
这里是我用来获得MS(毫秒):
迅速:
let startTime = NSDate().timeIntervalSince1970 * 1000
// your Swift code
let endTimeMinusStartTime = NSDate().timeIntervalSince1970 * 1000 - startTime
print("time code execution \(endTimeMinStartTime) ms")
objective - c:
double startTime = [[NSDate date] timeIntervalSince1970] * 1000.0;
// your Objective-C code
double endTimeMinusStartTime = [[NSDate date] timeIntervalSince1970] * 1000.0 - startTime;
printf("time code execution %f ms\n", endTimeMinusStartTime );
这里有另一种方法,在Swift中,使用defer关键字来做到这一点
func methodName() {
let methodStart = Date()
defer {
let executionTime = Date().timeIntervalSince(methodStart)
print("Execution time: \(executionTime)")
}
// do your stuff here
}
来自苹果的文档:defer语句用于在将程序控制权转移到该defer语句出现的范围之外之前执行代码。
这类似于try/finally块,优点是将相关代码分组。
我使用基于Ron的解决方案的宏。
#define TICK(XXX) NSDate *XXX = [NSDate date]
#define TOCK(XXX) NSLog(@"%s: %f", #XXX, -[XXX timeIntervalSinceNow])
对于代码行:
TICK(TIME1);
/// do job here
TOCK(TIME1);
我们将在控制台中看到如下内容:TIME1: 0.096618
下面是我使用的两个单行宏:
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])
像这样使用它:
TICK;
/* ... Do Some Work Here ... */
TOCK;
我知道这是一个旧的,但即使我发现自己又一次徘徊在它旁边,所以我想在这里提交我自己的选择。
最好的办法是看看我的博客文章: 在Objective-C中计时:秒表
基本上,我写了一个类,它以非常基本的方式停止观看,但被封装,所以你只需要做以下事情:
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
最后你会得到:
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
在日志里…
再一次,看看我的帖子,或者在这里下载: MMStopwatch.zip
推荐文章
- 如何删除默认的导航栏空间在SwiftUI导航视图
- 如何在iOS中使用Swift编程segue
- Swift -整数转换为小时/分钟/秒
- Swift:声明一个空字典
- 为什么ARC仍然需要@autoreleasepool ?
- 检测浏览器标签是否有焦点
- 在成功提交我的应用程序后,“太多符号文件”
- 首先添加一个UIView,甚至是导航栏
- 就性能而言,使用std::memcpy()还是std::copy()更好?
- 我如何改变UIButton标题颜色?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- CFNetwork SSLHandshake iOS 9失败