我正在从我的代码(用 java 编写)中调用一个函数,并且我想知道该函数正在使用多少内存,并且请记住,我无法向该函数(我正在调用)添加任何代码。
例如-
//my code starts
.
.
.
.
myfunc();
//print memory used by myfunc() here
.
.
// my code ends
这个怎么做?
我正在从我的代码(用 java 编写)中调用一个函数,并且我想知道该函数正在使用多少内存,并且请记住,我无法向该函数(我正在调用)添加任何代码。
例如-
//my code starts
.
.
.
.
myfunc();
//print memory used by myfunc() here
.
.
// my code ends
这个怎么做?
What you're trying to do is basically pointless. There is no such thing as memory used by a function. Your idea of comparing the total memory usage "before" and "after" function call does not have any sense: the function may change global state (which may decrease or increase total memory usage, and in some cases (e.g. cache filling) you probably won't want to consider the increase to count as "memory used by a function), or the garbage collector may run while you're inside of myfunc
and decrease the total used memory.
The good question often contains the large part of an answer. What you should do is to correctly ask the question.
我用这段代码成功了(不能保证它可以工作,但试试吧,它很有可能会给你你需要的东西):
final Runtime rt = Runtime.getRuntime();
for (int i = 0; i < 3; i++) rt.gc();
final long startSize = rt.totalMemory()-rt.freeMemory();
myFunc();
for (int i = 0; i < 3; i++) rt.gc();
System.out.println("Used memory increased by " +
rt.totalMemory()-rt.freeMemory()-startSize);
但它是错误的,因为理想情况下,减法后它应该始终为零。
实际上是正确的,因为通常每个线程都有一个 TLAB(线程本地分配缓冲区),这意味着它以块的形式分配(因此每个线程可以同时分配)
关闭它-XX:-UseTLAB
,您将看到分配的字节。
您应该多次运行它,因为使用此功能时可能会运行其他事情。