问题描述
我有一个占用大量CPU的任务,我希望它使用更少的CPU并占用更多时间.
I have a CPU intensive task and I want it to use less CPU and take up more time.
在启动时,我正在将大量SCNNode加载到场景中.它占用了大量内存,我希望它以安全的速率进行处理,而不是使系统滞后或使系统崩溃.
I'm loading a massive amount of SCNNodes to a scene at start-up. It takes up a lot of memory, and I'd like it to work on it at a safe rate instead of lagging up my system or potentially crashing it.
这是我用来加载节点的代码.
Here's the code I'm using to load the nodes.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){
NSLog(@"Start Loading Level");
SCNNode *cameraNode = [SCNNode node];
cameraNode.camera = [SCNCamera camera];
cameraNode.camera.zFar = 5000;
cameraNode.position = SCNVector3Make(0, 3000, 0);
cameraNode.rotation = SCNVector4Make(1, 0, 0, -M_PI_2);
[scene.rootNode addChildNode:cameraNode];
for (int i = 0; i < 100000; i++)
{
int side = 3000;
SCNNode *node = [SCNNode node];
node.geometry = [SCNBox boxWithWidth:1 height:1 length:1 chamferRadius:0];
node.position = SCNVector3Make(arc4random_uniform(side) - side / 2.0,
0,
arc4random_uniform(side) - side / 2.0);
[scene.rootNode addChildNode:node];
}
dispatch_async(dispatch_get_main_queue(), ^(void){
NSLog(@"Finished");
});
});
以下是统计数据:
推荐答案
这可能不是最好的方法,但是您是否看过prepareobject:
?
It might not be the best way to do this, but have you looked at prepareobject:
?
创建NSObjects本身不是什么大问题,但是准备几何并将其添加到场景中可能不是问题.如果将此步骤推迟到辅助线程,则可以节省一些CPU,并使场景直到准备好添加节点时才停止.
Creating the NSObjects themselves shouldn't be that much of a problem, but preparing the geometry and adding it to the scene probably is. Bu deffering this step to a secondary thread you'll save some CPU and make the scene not stop until the node is ready to be added.
每个节点准备就绪后,(完成处理程序)只需将其添加到场景中即可.我不会限制负载,但是对于您的其余应用程序,它至少会以一种更安全的方式处理它.
Once each node is ready, (completion handler) just add it to the scene. I won't throttle the loading, but it will at least handle it in a safer way for the rest of your app.
-(void)prepareLevel{
// Mutable Array to save the nodes
NSMutableArray *nodes = [[NSMutableArray alloc] init];
for (int i = 0; i < 100000; i++)
{
int side = 3000;
SCNNode *node = [SCNNode node];
node.geometry = [SCNBox boxWithWidth:1 height:1
length:1 chamferRadius:0];
node.position = SCNVector3Make(arc4random_uniform(side) - side / 2.0,
0,
arc4random_uniform(side) - side / 2.0);
[nodes addObject:node];
}
[mySCNView prepareObjects:nodes withCompletionHandler:^(BOOL success) {
for(SCNNode*node in nodes){
[scene.rootNode addChildNode:node];
}
}];
}
这篇关于后台线程上的节流CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!