Re: Optimizing jpeg recovery code
Quote:
Originally Posted by
VeNiX
So I should use sprintf() outside of the while loop to initialize all filenames first? or did you mean I should use something else entirely?
You should generate the file names up front before you enter code that is critical in terms of speed. You try to limit or eliminate the number of slow I/O or library calls in such code.
It may even be faster to generate all of your data in memory, and then once everything is done, write the whole memory block to the file at the end. Stuff like this:
Code:
if (found == false && num != 0)
{
fwrite(buffer, BLOCK, 1, jpeg);
}
Code:
if (num == 1)
{
jpeg = fopen(fileName, "w");
fwrite(buffer, BLOCK, 1, jpeg);
}
else
{
fclose(jpeg);
jpeg = fopen(fileName, "w");
fwrite(buffer, BLOCK, 1, jpeg);
}
Instead of immediately writing to a file, write to a some designated memory block, or even a memory mapped file, or something that goes to RAM and not the disk. Then when you are finished, then you create the new file and write the memory contents to a file.
Regards,
Paul McKenzie
Re: Optimizing jpeg recovery code
Paul is right to state that sprintf is 'a slow library function' and that its use in speed critical code could be problematic. However, the questions that need to be asked are 1) Is the code using sprintf critical in terms of speed? In your case I don't think it is particularly speed critical. 2) What is the general overhead of changing to something else? Paul suggests generating the file names up-front before the while loop is entered. In some situations this would work well, but in your case you don't know before running the program how many file names are needed. Your test file has 51 images, but what if the data was changed to contain 100, 1000, 100,000 images to be extracted? The overhead of the 'house-keeping' code could well exceed the expected speed improvements.
In your case if I was writing this program as a test for a CS course, I would leave the sprintf in the loop but explain in accompying documentation about the speed issue of using sprintf in the loop. Others may take a different view, but that is my humble opinion.