Я попытался создать MTLTexture (размер 1920x1080), и это стоит много времени при вызове [replaceRegion: mipmapLevel: withBytes: bytesPerRow], больше примерно 15 мс на моем iPhoneX. Есть ли способ улучшить производительность?
Вот мой тестовый код, я обнаружил, что, если я создаю текстуру в [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 будет стоить около 15 мс, в [Методе 2] функция mkTexture стоит всего 4 мс. Это действительно странно.