如何衡量UIImageView的绘制时间?

时间:2012-06-19 15:56:52

标签: iphone ios ipad uiimageview nsrunloop

我一直在努力追踪其中一个应用中的性能问题。似乎发生的事情是,有时UIImageView需要几秒钟来渲染图像,并且由于编写代码的方式,这会阻塞主线程。

我已经将这个问题追溯到这样一个事实:慢速图像是视网膜分辨率的渐进式JPEG。无论出于何种原因,当文件达到一定大小时,解码JPEG将成为一项非常昂贵的操作。

无论如何,在写simple test application的过程中,我意识到我不知道抽奖活动需要多长时间。它显然阻止了主线程,因此我决定尝试运行循环迭代。不幸的是,它最终有点hackish。这是相关的代码:

///////////////
//
// This bit is used to time the runloop. I don't know a better way to do this
// but I assume there is... for now... HACK HACK HACK. :-)

buttonTriggeredDate_ = [NSDate date];
[[NSRunLoop mainRunLoop] performSelector:@selector(fire:) target:self argument:[NSNumber numberWithInt:0] order:1 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];

///////////////

NSString* path = [[NSBundle mainBundle] pathForResource:imageName ofType:type];
self.imageView.image = [UIImage imageWithContentsOfFile:path];

回调如下(更多hackiness!):

- (void)fire:(NSNumber*)counter {
    int iterCount = [counter intValue];
    NSLog(@"mark %d", iterCount);
    NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:buttonTriggeredDate_];

    // We really need the second pass through - if it's less than X, assume
    // it's just that first runloop iteration before the draw happens. Just wait
    // for the next one.
    if (iterCount < 1) {
        iterCount++;
        [[NSRunLoop mainRunLoop] performSelector:@selector(fire:) 
                                          target:self 
                                        argument:[NSNumber numberWithInt:iterCount] 
                                           order:1 
                                           modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
    } else {
        self.statusDisplay.text = [NSString stringWithFormat:@"%@ - Took %f Seconds",
                                   self.statusDisplay.text,
                                   interv];
    }
}

所以,我的问题是,基本上,你会怎么做?我希望能够放入不同的图像并运行基准测试,以确保我大致了解运行它需要多长时间。我也希望它具有合理的一致性并且没有抖动。

嗯,也许我应该将UIImageView子类化并记录[super drawRect:frame]周围的时间?

你会做什么?

1 个答案:

答案 0 :(得分:1)

你可能会试图解决问题的错误部分。正如您所怀疑的那样,问题很可能出现在解码中(可能还有内存分配和复制)。问题不在于最终的“绘图”步骤本身。

这是为其构建的问题。启动仪器并寻找您的热点。

作为一种可能的解决方案,如果Instruments告诉您解码是阻止您的,那么您可以考虑将图像渲染到后台线程上的CALayer,然后再将它们放入视图中。