【问题标题】:Benchmark UIView drawRect: method基准 UIView drawRect: 方法
【发布时间】:2009-05-12 00:42:57
【问题描述】:

我正在用 Objective-C 编写一个 iPhone 应用程序,该应用程序在视图中使用了一些自定义绘图,我想对我的代码的各种修订进行基准测试,看看有什么真正有用的。我打算通过设置一个新应用程序来做到这一点,将我的自定义绘图代码添加到视图的 drawRect: 方法中,然后,在视图控制器的 for 循环中,发送[UIView setNeedsDisplay] 很多次并计时完成需要很长时间。然而,setNeedsDisplay 调用似乎被缓存了,所以即使我在 for 循环中调用它 1000 次,drawRect: 方法也只被调用一次。另外,我尝试直接调用 drawRect: 但我需要一个图形上下文来做一些绘图,当我不使用 setNeedsDisplay: UIGraphicsGetCurrentContext() 时不会给我一个上下文。

有什么建议吗?

谢谢,

凯尔

【问题讨论】:

    标签: iphone objective-c cocoa-touch benchmarking quartz-graphics


    【解决方案1】:

    您可以通过执行以下操作对视图进行基准测试:

    - (NSTimeInterval)timeTakenToDrawView:(UIView *)view count:(NSInteger)count
    {
        CGRect bounds = [view bounds];
        NSDate *startDate = [NSDate date];
        UIGraphicsBeginImageContext(bounds.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        NSInteger i = 0;
        for (i = 0; i < count; i++) {
            CGContextSaveGState(context);
            [view drawRect:bounds];
            CGContextRestoreGState(context);
        }
        UIGraphicsEndImageContext();
        return [[NSDate date] timeIntervalSinceDate:startDate];
    }
    

    (没试过,应该可以)

    【讨论】:

      【解决方案2】:

      在您的 NSView 的 .m 中。显然,您可能希望将其连接到 UI 或其他东西。

      - (void)awakeFromNib {
          // Have to wait for the window to be onscreen, graphics context ready, etc
          [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:NULL repeats:NO];
      }
      
      
      - (void)timerFired:(NSTimer *)aTimer {
          [self lockFocus];
      
          NSDate* then = [NSDate date];
      
          int callIdx = 0;
          for( callIdx = 0; callIdx < 1000; callIdx++ ) {
              [self drawRect:[self bounds]];
          }
          NSDate* now = [NSDate date];
      
          [self unlockFocus];
      
          NSLog(@"Took %f seconds", [now timeIntervalSinceDate:then]);
      }
      
      - (void)drawRect:(NSRect)rect {
          [[NSColor redColor] set];
          NSRectFill(rect);
      }
      

      【讨论】:

      • lockFocus 似乎在 UIViews 上不可用,此外,我需要某种方法来获取要在我的 drawRect: 函数中绘制的图形上下文,setNeedsDisplay 通过 UIGraphicsGetCurrentContext() 提供了一个但调用 drawRect:直接似乎没有做同样的事情。
      【解决方案3】:

      别忘了,如果你的 drawRect 经常使用,你也可以使用 CoreImage 性能工具来获取帧率。

      您还可以使用一些性能工具来查看该方法花费了多长时间。

      【讨论】:

        【解决方案4】:

        如果您正在寻找可以进行更深入分析的东西,我有一组宏可用于时间分析:https://gist.github.com/952456

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多