是否有一种方法可以确定一个方法需要执行多少时间(以毫秒为单位)?
当前回答
我在我的utils库中使用这个(Swift 4.2):
public class PrintTimer {
let start = Date()
let name: String
public init(file: String=#file, line: Int=#line, function: String=#function, name: String?=nil) {
let file = file.split(separator: "/").last!
self.name = name ?? "\(file):\(line) - \(function)"
}
public func done() {
let end = Date()
print("\(self.name) took \((end.timeIntervalSinceReferenceDate - self.start.timeIntervalSinceReferenceDate).roundToSigFigs(5)) s.")
}
}
…然后调用如下方法:
func myFunctionCall() {
let timer = PrintTimer()
// ...
timer.done()
}
…运行后在控制台中看起来是这样的:
MyFile.swift:225 - myFunctionCall() took 1.8623 s.
虽然不像上面的TICK/TOCK那样简洁,但它足以清楚地看到它在做什么,并自动包括正在计时的内容(通过文件、方法开头的行和函数名)。显然,如果我想要更多的细节(例如,如果我不只是计时一个方法调用,因为是通常的情况下,而是在该方法内计时块),我可以在PrintTimer init上添加“name="Foo""参数来命名它除了默认值之外的东西。
其他回答
你可以得到很好的时间(秒。部分秒)使用这个StopWatch类。它使用了iPhone的高精度计时器。使用NSDate只能获得秒级精度。这个版本是专门为自动发布和objective-c设计的。如果需要的话,我也有一个c++版本。你可以在这里找到c++版本。
StopWatch.h
#import <Foundation/Foundation.h>
@interface StopWatch : NSObject
{
uint64_t _start;
uint64_t _stop;
uint64_t _elapsed;
}
-(void) Start;
-(void) Stop;
-(void) StopWithContext:(NSString*) context;
-(double) seconds;
-(NSString*) description;
+(StopWatch*) stopWatch;
-(StopWatch*) init;
@end
StopWatch.m
#import "StopWatch.h"
#include <mach/mach_time.h>
@implementation StopWatch
-(void) Start
{
_stop = 0;
_elapsed = 0;
_start = mach_absolute_time();
}
-(void) Stop
{
_stop = mach_absolute_time();
if(_stop > _start)
{
_elapsed = _stop - _start;
}
else
{
_elapsed = 0;
}
_start = mach_absolute_time();
}
-(void) StopWithContext:(NSString*) context
{
_stop = mach_absolute_time();
if(_stop > _start)
{
_elapsed = _stop - _start;
}
else
{
_elapsed = 0;
}
NSLog([NSString stringWithFormat:@"[%@] Stopped at %f",context,[self seconds]]);
_start = mach_absolute_time();
}
-(double) seconds
{
if(_elapsed > 0)
{
uint64_t elapsedTimeNano = 0;
mach_timebase_info_data_t timeBaseInfo;
mach_timebase_info(&timeBaseInfo);
elapsedTimeNano = _elapsed * timeBaseInfo.numer / timeBaseInfo.denom;
double elapsedSeconds = elapsedTimeNano * 1.0E-9;
return elapsedSeconds;
}
return 0.0;
}
-(NSString*) description
{
return [NSString stringWithFormat:@"%f secs.",[self seconds]];
}
+(StopWatch*) stopWatch
{
StopWatch* obj = [[[StopWatch alloc] init] autorelease];
return obj;
}
-(StopWatch*) init
{
[super init];
return self;
}
@end
该类有一个返回自动释放对象的静态stopWatch方法。
调用start后,使用seconds方法获取运行时间。再次调用start来重新启动它。或者停下来停下来。在调用stop后,您仍然可以随时读取时间(调用秒数)。
函数中的示例(执行的定时调用)
-(void)SomeFunc
{
StopWatch* stopWatch = [StopWatch stopWatch];
[stopWatch Start];
... do stuff
[stopWatch StopWithContext:[NSString stringWithFormat:@"Created %d Records",[records count]]];
}
在Swift中,我使用:
在我的Macros.swift中,我刚刚添加了
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__){
println("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
你现在可以在任何地方打电话
TICK()
// your code to be tracked
TOCK()
斯威夫特5.0
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = #function, file: String = #file, line: Int = #line){
print("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
这段代码是基于Ron的代码翻译成Swift的,他有功劳 我在全球范围内使用开始日期,任何改进建议都是欢迎的
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")
对于OS X上的细粒度计时,您应该使用在<mach/mach_time.h>中声明的mach_absolute_time():
#include <mach/mach_time.h>
#include <stdint.h>
// Do some stuff to setup for timing
const uint64_t startTime = mach_absolute_time();
// Do some stuff that you want to time
const uint64_t endTime = mach_absolute_time();
// Time elapsed in Mach time units.
const uint64_t elapsedMTU = endTime - startTime;
// Get information for converting from MTU to nanoseconds
mach_timebase_info_data_t info;
if (mach_timebase_info(&info))
handleErrorConditionIfYoureBeingCareful();
// Get elapsed time in nanoseconds:
const double elapsedNS = (double)elapsedMTU * (double)info.numer / (double)info.denom;
当然,关于细粒度度量的通常警告也适用;您可能最好多次调用测试中的例程,并求平均值/取最小值/一些其他形式的处理。
此外,请注意,您可能会发现使用Shark等工具对应用程序运行进行概要分析更有用。这不会为您提供确切的时间信息,但它会告诉您应用程序的时间在哪里花费了多少百分比,这通常更有用(但并不总是如此)。
我使用非常少的,一页的类实现,灵感来自这篇博客文章的代码:
#import <mach/mach_time.h>
@interface DBGStopwatch : NSObject
+ (void)start:(NSString *)name;
+ (void)stop:(NSString *)name;
@end
@implementation DBGStopwatch
+ (NSMutableDictionary *)watches {
static NSMutableDictionary *Watches = nil;
static dispatch_once_t OnceToken;
dispatch_once(&OnceToken, ^{
Watches = @{}.mutableCopy;
});
return Watches;
}
+ (double)secondsFromMachTime:(uint64_t)time {
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
return (double)time * (double)timebase.numer /
(double)timebase.denom / 1e9;
}
+ (void)start:(NSString *)name {
uint64_t begin = mach_absolute_time();
self.watches[name] = @(begin);
}
+ (void)stop:(NSString *)name {
uint64_t end = mach_absolute_time();
uint64_t begin = [self.watches[name] unsignedLongLongValue];
DDLogInfo(@"Time taken for %@ %g s",
name, [self secondsFromMachTime:(end - begin)]);
[self.watches removeObjectForKey:name];
}
@end
它的用法很简单:
调用[DBGStopwatch start:@"slow-operation"];一开始 然后[DBGStopwatch stop:@"slow-operation"];做完之后,才能得到时间
推荐文章
- CFNetwork SSLHandshake iOS 9失败
- 如何解析unix时间戳到时间。时间
- 如何使用yyyyMMddHHmmss格式格式化当前时间?
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- MySQL OR与IN性能
- Xcode构建失败“架构x86_64未定义的符号”
- 前一个月的Python日期
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持