创建MTLTexture需要花费大量时间,如何改进呢?

时间:2019-01-20 03:54:14

标签: performance metal

我试图创建一个MTLTexture(大小为1920x1080),并且在调用[replaceRegion:mipmapLevel:withBytes:bytesPerRow]时花费很多时间,在我的iPhoneX上大约需要15ms。有什么方法可以提高性能?

这是我的测试代码,我发现,如果我在[viewDidAppear]中制作纹理,则只需花费约4毫秒的时间。有什么区别?

#import "ViewController.h"
#import <Metal/Metal.h>
#define I_WIDTH 1920
#define I_HEIHG 1080

@interface ViewController ()
@property(strong, nonatomic) id<MTLDevice> device;
@property(strong, nonatomic) NSTimer* timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.device = MTLCreateSystemDefaultDevice();
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //Method 1. This would run really slow, aboult 15ms per loop
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(mkTexture) userInfo:nil repeats:true];
    //Method 2. This would run really fast, aboult 3ms per loop
//    for (int i = 0; i < 3000; i++) {
//        [self mkTexture];
//    }
}

- (void)mkTexture {
    double start = CFAbsoluteTimeGetCurrent();
    MTLTextureDescriptor* desc = [[MTLTextureDescriptor alloc] init];
    desc.width = I_WIDTH;
    desc.height = I_HEIHG;
    desc.pixelFormat = MTLPixelFormatBGRA8Unorm;
    desc.usage = MTLTextureUsageShaderRead;
    id<MTLTexture> texture = [self.device newTextureWithDescriptor:desc];
    char* bytes = (char *)malloc(I_WIDTH * I_HEIHG * 4);
    [texture replaceRegion:MTLRegionMake3D(0, 0, 0, I_WIDTH, I_HEIHG, 1) mipmapLevel:0 withBytes:bytes bytesPerRow:I_WIDTH * 4];
    double end = CFAbsoluteTimeGetCurrent();
    NSLog(@"%.2fms", (end - start) * 1000);
    free(bytes);
}

@end

使用[方法1]时,函数mkTexture将花费大约15ms,对于[方法2],功能mkTexture将仅花费4ms。真的很奇怪。

0 个答案:

没有答案