首页 > 解决方案 > 创建 MTLTexture 需要花费大量时间,如何改进它?

问题描述

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

这是我的测试代码,我发现,如果我在 [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。这真的很奇怪。

标签: performancemetal

解决方案


推荐阅读