How to Optimize mach_msg_trap

2019-07-06 00:05发布

问题:

I know this question has been asked before, but no one has given any helpful answers as to how to fix it. I have a cocos2d ios application that uses the box2d physics engine. I ran a performance test on it and the cpu spends 5.6% of its time on mach_msg_trap. From what I have gathered from other questions, it seems as if mach_msg_trap is just the main thread waisting time as a result of your application being idle. My application isn't idle though. It has shaky performance and hovers in the 50 fps area. Is there some way to configure this to gain extra performance? Or is this just a result of some bad code i wrote and if so how do I optimize it?


I am testing the performance in the debug build on an ipod touch second generation. This might be part of the problem. I am grouping certain things in sprite batches. But some sprites have children that aren't ccsprites so I can't group everything in one single batch. I do create a pool of bullets instead of allocing and releasing them constantly. But this is where I get the shaky performance. When a gun starts firing the framerate drops 10-15 fps. I tried to track what was taking so long using instruments but the top two time waisters are glValidateState, which includes ccsprite draw and ccnode visit. The second beggest time waister is mach_msg_trap. Is there any other way to find out what it is in the bullet's code that is slowing the performance down? By the way your book was really helpful in learning cocos2d:)

回答1:

Have you read the answer to this question?

mach_msg_trap is not wasting time being idle. It's a function that waits for some result before the application's process can continue with normal execution. Of course it will also run when your app is idle, but I doubt that this is the case for you. Instead those 5% may come from waiting for disk I/O for example when loading a file from flash memory.

If your performance is "shaky" I wouldn't waste time trying to find the fault in system level functions that you can't modify or configure.

Secondly, you haven't mentioned where you are measuring the performance, ie which device. If you get 50 fps on an iPhone 3G or older the performance could even be considered good. In addition you should measure performance only in release builds.

Personally I can only recommend to check that you've followed best practices, like using sprite sheets and a texture atlas for your sprites, pooling sprites and physics objects instead of creating and releasing them frequently, and reducing the number of iterations Box2D is running in its step function.