performance - 创建 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。这真的很奇怪。
解决方案
推荐阅读
- python - 迭代 Python 列表并删除每个子列表的最终索引,无导入
- sql-server - 使用 SSIS 从经过身份验证的 url 下载文件时出错
- java - 我可以用什么来模拟无穷大?
- python - 列表中 x 元素的最后 3 个元素的总和作为新列表 [python 3]
- javascript - 欧拉项目#5 递归?
- architecture - 我应该在不同的主机中制作管理面板吗?
- html - Selenium Python3 从 Chrome 中抓取标签外的文本
- angular - 使用分页搜索表 - 仅搜索第一页
- python - 通过解析文件列出超出范围的索引
- elasticsearch - 用户数据覆盖的 Elasticsearch 查询