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

问题描述:

我定义TOOLS_COMPUTE_TIME这样如何制作一个宏来计算block的时间?

#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 *不是它。什么?

问题是C预处理器不能理解obj-c语法。你可以告诉它你的宏需要解决这个可变参数

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

这样,它会采取什么都在括号之间,并把它传递。如果你有一个不平衡的结束圆括号,这只会失败,但它会失败,但你可能会以这种方式得到一个好奇的编译器错误。

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

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

+0

哈,我刚刚意识到你的问题实际上是[我的错](http://*.com/questions/7411027/how-to-nslog-calling-function/7411041#7411041)。我应该编辑该答案以使用可变参数宏。 –

+0

我将使用#define TOOLS_COMPUTE_TIME(...)[Tools computeTimeWithName:[NSString stringWithFormat:@“%s”,__ PRETTY_FUNCTION__] block:(__ VA_ARGS__)] –