- Home /
What is the bottleneck in this iphone code?
I'm trying to grab screenshots using the script below on the iphone. Application.captureScreenshot works faster than this code on the iphone but then I can't control the capture area. Both are really slow on the iphone 4s like 1.5 frames per second. I'm wondering if there is any way to speed this up using any new features in the pro version?
import System;
import System.IO;
function UploadPNG () {
// Create a texture the size of the screen, RGB24 format
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels (Rect(0, 0, width, height), 0, 0);
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Destroy (tex);
File.WriteAllBytes(Application.dataPath+"Documents/screenpng"+screencounter+".png", bytes);
}
}
Well by profiling do you mean commenting out everything one at a time to see how much the speed changes? Or is there a more scientific way? In my tests so far ReadPixels is the slowest operation. Is it possible to find a faster operation?
Answer by Statement · Mar 22, 2012 at 05:32 PM
What is the bottleneck in this iphone code?
Profile the code. It's good exercise and will answer your question.
Answer by tomka · May 23, 2012 at 04:33 AM
Split the file saving out into a thread. This code will still be slow, but at least you won't be stalling the update loop while writing to disk.
Does the iphone do threads? If so can you point me to an example. I've never looked into that technique in unity. Thanks for the idea.
Yeah the iPhone can do threads.
Something like...
using System.Threading; at the top
and
class FileWriter { public FileWriter(byte[] bytes, string filename) { this.filename = new string(filename); //clone for thread safety this.bytes = new byte[bytes.Length]; //clone for thread safety bytes.CopyTo(this.bytes, 0) ; }
public void WriteToDisk() { System.IO.File.WriteAllBytes(filename, bytes); } }
FileWriter writer = new FileWriter(); Thread myFileWriterThread = new Thread(writer.WriteToDisk); myFileWriterThread.Start();
That's more or less it. $$anonymous$$SDN's C# reference has some better examples but their API docs suck.
...apologies for the formatting. Apparently writing this as a comment ruins it.
Answer by kirpigiller · May 23, 2012 at 05:17 AM
tex.ReadPixels and File.WriteAllBytes unfortunately there is no way to really speed up capturing. Especially on iPhone.