1

Is it possible to know/get how much space/memory are used when a method is executed or when there is a return value? I don't want to know how much space used by the app, just some code like method or the return value. I tried the runtime.getRuntime, but from my understanding, It looks like it tells me how much space is used by the entire code/app, am I right?

EDIT :

  public int [] randtotal(int times2)
    {
        int in1[] = new int[times2];
        for (int i = 0; i<Num2; i++)
        Random rand = new Random();
        {
            in1[times2]= rand.NextInt(5);
        }

        totalNum(in1);
        return int1;
    }   

As you can see here, at the end of the code there is the "return int1;" , so I want to know when these code is executed how much space is allocated for the value here?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • "The method _or_ the return value"? It's hard to understand what you really mean with this. Care to show an example? – E_net4 Oct 01 '15 at 14:32
  • Options include: 1) Use a profiler externally. 2) Take the difference between measurements of used memory internally. 3) Estimate the size of objects as discussed in this question: http://stackoverflow.com/questions/4115239/sizeof-java-object . – Andy Thomas Oct 01 '15 at 14:37
  • 2
    You should add your code samples by editing your question not in the comments :) – Arkantos Oct 01 '15 at 14:37
  • I'm sorry sir, I already add the sample code, thanks. – user5397881 Oct 01 '15 at 14:39
  • `int inputData[] = new int[Num2]` - As you're creating an int Array here, the memory occupied by this Array depends on the value of `Num2` here. Let's say `Num2` is 10 i.e you're creating an array of 10 ints - so it will be `12 bytes (Header) + 4 bytes (length) + 10 * 4 bytes (each int is 4 bytes) = 56 bytes` – Arkantos Oct 01 '15 at 14:42
  • I see. Thanks for the explanation, but is there a way you can get the 56 bytes answer with a code? Something like sizeof or runtime.getRuntime maybe? – user5397881 Oct 01 '15 at 14:43
  • You can try Java Object Layout API from [here](http://openjdk.java.net/projects/code-tools/jol/). I cannot assure you that it returns exactly 56 bytes from code :) – Arkantos Oct 01 '15 at 14:45
  • But I think you will get even better picture if you use a profiling tool like VisualVM , Eclipse MAT or YourKit Java Profiler (Commercial). You can use any of these tools, take a Heap Snapshot and then analyze object sizes, instance count and several other metrics :) – Arkantos Oct 01 '15 at 14:49
  • Thanks a lot sir and anyone else that reply to this problem, I will try your suggestion and see if it works for me. thanks again. – user5397881 Oct 01 '15 at 14:54

1 Answers1

2

You can use Visualvm tool to profile the overall application and you can also profile certain package, class or function

see this link : https://visualvm.java.net/profiler.html

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39