简体   繁体   English

检查java中使用的bufferedImage内存量是多少?

[英]Check how much memory bufferedImage in java uses?

I have a bufferedImage in Java. 我在Java中有一个bufferedImage。 How do I see how much memory it takes up? 我怎么看它占用了多少内存? Thanks in advance. 提前致谢。

You can determine how many bytes the image data alone takes up using this: 您可以使用以下方法确定图像数据单独占用的字节数:

DataBuffer buff = image.getRaster().getDataBuffer();
int bytes = buff.getSize() * DataBuffer.getDataTypeSize(buff.getDataType()) / 8;

The image itself takes up a bit more space for the color model and other bookkeeping info, but for large images, bytes will be the dominant term. 图像本身为颜色模型和其他簿记信息占用了更多空间,但对于大图像, bytes将是主要术语。

I'm not sure there's a straight-forward way to figure this out with 100% accuracy down to the number of bytes, without calculating it yourself (taking into account the color model, the size of the image, and other factors). 我不确定是否有一种直接的方法来解决这个问题,100%的准确度低至字节数,而不是自己计算(考虑到颜色模型,图像大小和其他因素)。

You can calculate the totalMemory() and freeMemory() on the heap before and after allocation, and get an estimate that way. 您可以在分配之前和之后计算堆上的totalMemory()和freeMemory() ,并以此方式获得估计。 If other objects are allocated (or collected) between your checks, your calculation won't be accurate. 如果在您的支票之间分配(或收集)其他对象,则您的计算将不准确。

This discussion talks about the size of primitive types in the JVM (an object being a collection of many primitive objects), which you can use to figure this out. 这个讨论讨论了JVM中的原始类型的大小(一个对象是许多原始对象的集合),您可以使用它来解决这个问题。

This article give an overview of memory usage in Java. 本文概述了Java中的内存使用情况。

Using Runtime#totalMemory and Runtime#gc should be able to get you a very close approximation. 使用Runtime#totalMemoryRuntime#gc应该可以得到非常接近的近似值。 Example: 例:

Runtime.getRuntime().gc();Runtime.getRuntime().gc();Runtime.getRuntime().gc();
long totalUsed = Runtime.getRuntime().totalMemory();

BufferedImage image = ...

Runtime.getRuntime().gc();Runtime.getRuntime().gc();Runtime.getRuntime().gc();
totalUsed = Runtime.getRuntime().totalMemory() - total;

Calling gc multiple times increases the chance that the garbage collector will actually run, since gc is just a suggestion. 多次调用gc增加垃圾收集器实际运行的几率,因为gc只是一个建议。 Calling gc in this example ensures that no objects that would have been collected are adding to memory usage. 在此示例中调用gc可确保没有收集的对象正在添加内存使用情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM