1

Is it as simple as calling memory_get_usage() at the start and end of a script and subtracting the 1st from the second value, to get the total memory used on that script? If so, how can I convert that value to a more understandable number like kb and mb?

1
  • If you have a Meta Stack Overflow account, it would be nice if you linked them. Commented Aug 3, 2009 at 18:47

2 Answers 2

6

You mean something like this?

function file_size($size)
{
    $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) .$filesizename[$i] : '0 Bytes';
}

I normally use this to format file sizes, but you can use it to solve your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Why are you dividing by 1024 multiple times when you can just use the number in your if sentence? And its really KiB, MiB, GiB and TiB for binary (1024) and for decimal (1000) its kB (note lower k), MB, GB and TB.
3

You may prefer to just call memory_get_peak_usage at the end of your script, which will return the highest total allocation during execution. This is more likely to be a useful figure - getting the start and end values doesn't account for memory allocated then deallocated during runtime.

Formatting this into a human readable number can be handled manually (just divide by 1024 then print as Kb), or with a class like NumberFormatter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.