开发者

How to make a macro to computeTime of block?

I am define TOOLS_COMPUTE_TIME like this

#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);
}

and then when I call:

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]];
}];

it's still have many error.. like "Macro "TOOLS_C开发者_如何学PythonOMPUTE_TIME" passed 4 arguments, but takes just 1"

something like that code have many argument, but I think that code pass just one argument like block

anyone can help me to fix it?

Another error seems to be on the type of PRETTY_FUNCTION It's not NSString * isn't it. What?


The problem is the C Preprocessor isn't savvy with obj-c syntax. You can get around this by telling it your macro takes varargs

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

This way it'll take anything at all between the parens and pass it on. This will only fail if you have an unbalanced end parenthesis, which should fail anyway but you'll probably get a curious compiler error this way.

As for the string error, PRETTY_FUNCTION is a C String (e.g. char*), not an NSString. Either rewrite your +[Tools computeTimeWithName:block:] function to take a char* as it's first argument, or pass [NSString stringWithUTF8String:__PRETTY_FUNCTION__] instead (the former is easier, just change the format token for your log to %s instead of %@).

As a side note, NSDate isn't ideal for computing runtimes, since it's based on the clock time which is subject to drift (intentional or otherwise) and which could change on you. You should base yourself on mach absolute time instead. Luckily for you, CoreAnimation has a convenience function CACurrentMediaTime which returns mach absolute time expressed as a CFTimeInterval (e.g., in seconds). You can use this instead to figure out a reliable runtime for a block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜