如何制作一个宏来计算块的时间?

时间:2011-09-20 05:48:05

标签: objective-c objective-c-blocks

我像这样定义TOOLS_COMPUTE_TIME

#define TOOLS_COMPUTE_TIME(op) [Tools computeTimeWithName:__PRETTY_FUNCTION__ block:(op)]

+(void)computeTimeWithName:(NSString *) caller block:(void (^)())block
{
    NSDate * currentTime = [NSDate date];
    block();
    DLog(@"Time Running is: %f", [[NSDate date] timeIntervalSinceDate:currentTime]);
    DLog(@"Caller : %@", caller);
}

然后我打电话:

TOOLS_COMPUTE_TIME(^{

});

[Tools computeTimeWithName:ThisFunction block:^{
    //I want to move this blog on top
    NSString * urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",[BNUtilitiesQuick UtilitiesQuick].currentAnchor.coordinate.latitude,[BNUtilitiesQuick UtilitiesQuick].currentAnchor.coordinate.longitude];
    NSURL * Url= [NSURL URLWithString:urlString];
    NSString * result = [NSString stringWithContentsOfURL:Url encoding:NSASCIIStringEncoding error:nil];
    NSArray *lines = [result componentsSeparatedByString:@","];
    locationString =[NSString stringWithFormat:@"%@\"",[lines objectAtIndex:2]];
}];

它仍然有很多错误..就像“宏”TOOLS_COMPUTE_TIME“传递4个参数,但只需要1”

类似代码的东西有很多参数,但我认为代码只传递一个像块

这样的参数

任何人都可以帮我修理它吗?

另一个错误似乎是 PRETTY_FUNCTION 的类型。它不是NSString *不是它。什么?

1 个答案:

答案 0 :(得分:3)

问题是C预处理器不熟悉obj-c语法。你可以告诉它你的宏需要varargs来解决这个问题

#define TOOLS_COMPUTE_TIME(...) [Tools computeTimeWithName:__PRETTY_FUNCTION__ block:(__VA_ARGS__)]

通过这种方式,它可以在parens之间采取任何措施并传递它。如果你有一个不平衡的末端括号,这只会失败,无论如何都应该失败,但你可能会以这种方式得到一个奇怪的编译器错误。

对于字符串错误, PRETTY_FUNCTION 是C字符串(例如char*),而不是NSString。要么重写+[Tools computeTimeWithName:block:]函数以取char*作为第一个参数,要么改为[NSString stringWithUTF8String:__PRETTY_FUNCTION__](前者更容易,只需将日志的格式标记更改为%s而不是%@)。

作为旁注,NSDate不是计算运行时的理想选择,因为它基于时钟时间,该时间可能会发生漂移(有意或无意),并且可能会对您产生影响。你应该以mach absolute time为基础。幸运的是,CoreAnimation有一个便利函数CACurrentMediaTime,它返回表示为CFTimeInterval的马赫绝对时间(例如,以秒为单位)。您可以使用它来为块找出可靠的运行时。