How to get actual RAM usage of app in android? - java

Quite simply, how can I get the amount of memory (in MB) that my android app is currently using? This would need to be done in Java so I can display this information to the user.
I've looked at other stackoverflow posts but none give a simple or accurate answer to this problem.

adb shell dumpsys meminfo packagename
Try to execute this command with Java.

You can use ActivityManager for that purpose.
It's answered in this post.

Try to use this code if a performance is not critical:
Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memInfo);
long res = memInfo.getTotalPrivateDirty();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
res += memInfo.getTotalPrivateClean();
return res * 1024L;
If performance is critical check this answer

1. dumpsys meminfo PKG_NAME
...
App Summary
Pss(KB)
------
Java Heap: 42868 <--
Native Heap: 52268 <--
Code: 23608
Stack: 96
Graphics: 5084
Private Other: 5620
System: 14900
TOTAL: 144444 <-- TOTAL SWAP PSS: 130
2. in java code
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Debug.java#640
// this is the value source of dumpsys meminfo.
Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memInfo);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
String javaMem = memInfo.getMemoryStat("summary.java-heap");
String natiMem = memInfo.getMemoryStat("summary.native-heap");
String totalMem = memInfo.getMemoryStat("summary.total-pss");
//msg2 += "\n" + String.format("%s %s %s", javaMem, natiMem, totalMem);
msg2 += "\n\n"+String.format("java %8s\nnati %8s\ntotal %8s",
formatMB(Integer.parseInt(javaMem)), formatMB(Integer.parseInt(natiMem)), formatMB(Integer.parseInt(totalMem))
);
}
...
String formatMB(double KB){
return String.format("%.1f MB", KB/1024);
}
The other api need lots of calculate,
// you can read them in Debug.java src file.
This is the closest to dumpsys meminfo or android studio monitor.

Related

Power consumption of virtual machines in Cloudsim

Can we add a powerModel for virtual machine also as we do it for host in Cloudsim (simulation Tool)? So that we can track the power consumption of each virtual machines.
Using CloudSim Plus you can compute the CPU usage and power consumption of a VM using the following code into your example:
private void printVmsCpuUtilizationAndPowerConsumption() {
for (Vm vm : vmList) {
System.out.println("Vm " + vm.getId() + " at Host " + vm.getHost().getId() + " CPU Usage and Power Consumption");
double vmPower; //watt-sec
double utilizationHistoryTimeInterval, prevTime = 0;
final UtilizationHistory history = vm.getUtilizationHistory();
for (final double time : history.getHistory().keySet()) {
utilizationHistoryTimeInterval = time - prevTime;
vmPower = history.powerConsumption(time);
final double wattsPerInterval = vmPower*utilizationHistoryTimeInterval;
System.out.printf(
"\tTime %8.1f | Host CPU Usage: %6.1f%% | Power Consumption: %8.0f Watt-Sec * %6.0f Secs = %10.2f Watt-Sec\n",
time, history.vmCpuUsageFromHostCapacity(time) *100, vmPower, utilizationHistoryTimeInterval, wattsPerInterval);
prevTime = time;
}
System.out.println();
}
}
You don't implement specific PowerModel for VMs. The VM power consumption is determined by its CPU utilization and the Host's PowerModel.
You can get the complete example here.

Start Java Application using System.Diagnostics.Process

$startCount = 5;
$processors = Get-WmiObject -Class Win32_ComputerSystem | select -
ExpandProperty "NumberOfLogicalProcessors";
$perInstance = $processors / $startCount;
$affinityloop = 1;
$affinityvalue = 0;
for($i=1; $i -le $startCount; $i++) {
$affinityvalue = 0;
for($u=1; $u -le $perInstance ; $u++) {
$affinityvalue = $affinityvalue + $affinityloop;
$affinityloop = $affinityloop * 2;
}
$ps = new-object System.Diagnostics.Process;
$ps.StartInfo.Filename = "C:\jdk\bin\java.exe";
$ps.StartInfo.Arguments = " -server -Xms10240m -Xmx10240m -XX:+UseG1GC -cp `".;*`" Worker";
$ps.start();
Write-Host $affinityvalue ;
$ps.ProcessorAffinity = [Convert]::ToString($affinityvalue, 16);
}
I am trying to start a Windows Java application on two different NUMA nodes. Has anyone able to accomplish this with Diagnostics.Process format? This code does work fine, but all applications created are on the same NUMA node and hence only using 50% power.
I tried codes such as $mod = ($i % 2); to help prepare for some way to alternate the NUMA node but unsure how to specify it within the script.
EDIT
Tried to load balance with ProcessorAffinity and I get crashes due to Double unable to convert to IntPtr
EDIT 2
So it looks like Windows Groups the processors past 64 into Groups. Can't seem to find a way to alter that like ProcessAffinity. I guess its just not that common. You can easily do it in Task manager, just need to find a way to do it in Powershell or similar.

Why zabbix do not show a value received from java code?

Consider a java code:
String host = "zabbixHost";
int port = 10051;
ZabbixSender zabbixSender = new ZabbixSender(host, port);
DataObject dataObject = new DataObject();
dataObject.setHost("testHost");
dataObject.setKey("test.ping.count");
dataObject.setValue("10");
// TimeUnit is SECONDS.
dataObject.setClock(System.currentTimeMillis()/1000);
SenderResult result = zabbixSender.send(dataObject);
System.out.println("result:" + result);
if (result.success()) {
System.out.println("send success.");
} else {
System.err.println("sned fail!");
}
The result is {"failed":0,"processed":1,"spentSeconds":0.001715,"total":1}
Then I send a request by zabbix_sender tool from command line:
zabbix_sender -z zabbixHost -p 10051 -s testHost -k test.ping.count -o 8 -v
The output is:
info from server: "processed: 1; failed: 0; total: 1; seconds spent: 0.002052"
sent: 1; skipped: 0; total: 1
For now 2 values were sent into Zabbix. But when I got to the monitoring graphic for test.ping.count and only 8 value is shown. E.g. value from java code was not received even when response was successful.
What is going on? How to fix such situation?
Note
The library is - io.github.hengyunabc:zabbix-sender:0.0.3
Zabbix version is 3.0
The problem was with timestamps, zabbix-sender with version 0.0.1 set request (not dataobject) clock in milliseconds while version 0.0.3 in seconds. So using right version fix issues.
maven sample (source):
<dependency>
<groupId>io.github.hengyunabc</groupId>
<artifactId>zabbix-sender</artifactId>
<version>0.0.3</version>
</dependency>

Tuprolog and defining infix operators

So I have some prolog...
cobrakai$more operator.pl
be(a,c).
:-op(35,xfx,be).
+=(a,c).
:-op(35,xfx,+=).
cobrakai$
Which defines some infix operators. I run it using SWI prolog and get the following (perfectly expected) results
?- halt.
cobrakai$swipl -s operator.pl
% library(swi_hooks) compiled into pce_swi_hooks 0.00 sec, 3,992 bytes
% /Users/josephreddington/Documents/workspace/com.plancomps.prolog.helloworld/operator.pl compiled 0.00 sec, 992 bytes
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.10.5)
Copyright (c) 1990-2011 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
?- be(a,c).
true.
?- a be c.
true.
?- +=(a,c).
ERROR: toplevel: Undefined procedure: (+=)/2 (DWIM could not correct goal)
?- halt.
cobrakai$swipl -s operator.pl
% library(swi_hooks) compiled into pce_swi_hooks 0.00 sec, 3,992 bytes
% /Users/josephreddington/Documents/workspace/com.plancomps.prolog.helloworld/operator.pl compiled 0.00 sec, 1,280 bytes
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.10.5)
Copyright (c) 1990-2011 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
?- be(a,c).
true.
?- a be c.
true.
?- +=(a,c).
true.
?- a += c.
true.
?- halt.
However, when I use Tuprolog to process the same file from Java (using the following code)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import alice.tuprolog.Prolog;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Theory;
public class Testinfixoperatorconstruction {
public static void main(String[] args) throws Exception {
Prolog engine = new Prolog();
engine.loadLibrary("alice.tuprolog.lib.DCGLibrary");
engine.addTheory(new Theory(readFile("/Users/josephreddington/Documents/workspace/com.plancomps.prolog.helloworld/operator.pl")));
SolveInfo info = engine.solve("be(a,c).");
System.out.println(info.getSolution());
info = engine.solve("a be c.");
System.out.println(info.getSolution());
}
private static String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
}
}
The prolog file does not parse - failing on the '+=' token.
Exception in thread "main" alice.tuprolog.InvalidTheoryException: Unexpected token '+='
at alice.tuprolog.TheoryManager.consult(TheoryManager.java:193)
at alice.tuprolog.Prolog.addTheory(Prolog.java:242)
at Testinfixoperatorconstruction.main(Testinfixoperatorconstruction.java:14)
We can try a slightly different approach, adding the operator directly in the java code with...
public static void main(String[] args) throws Exception {
Prolog engine = new Prolog();
engine.loadLibrary("alice.tuprolog.lib.DCGLibrary");
engine.getOperatorManager().opNew("be", "xfx", 35);
engine.getOperatorManager().opNew("+=", "xfx", 35);
engine.addTheory(new Theory(
readFile("/Users/josephreddington/Documents/workspace/com.plancomps.prolog.helloworld/operator2.pl")));
SolveInfo info = engine.solve("be(a,c).");
System.out.println(info.getSolution());
info = engine.solve("a be c.");
System.out.println(info.getSolution());
}
but we get the same error... :(
Can anyone tell me why this is happening? (and solutions would also be welcome).
SWI-Prolog could be too much permissive while parsing directives. Try enclosing operators between parenthesis:
:-op(35,xfx,(+=)).
edit I tried using 2p.jar, that allowed me to spot the problem. Need to quote operator' atom:
:-op(35,xfx, '+=').
X += Y.
p :- a += b.
interactive 2p console accepts this syntax. Note that 2p.jar by default load tuprolog libraries

How to get Ram size and size of Hard disk using Java?

How to get the Ram size and Hard disk size of the PC using Java? And Is it possible to get the currently logged user name on PC through java?
Disk size:
long diskSize = new File("/").getTotalSpace();
User name:
String userName = System.getProperty("user.name");
I'm not aware of a reliable way to determine total system memory in Java. On a Unix system you could parse /proc/meminfo. You can of course find the maximum memory available to the JVM:
long maxMemory = Runtime.getRuntime().maxMemory();
Edit: for completeness (thanks Suresh S), here's a way to get total memory with the Oracle JVM only:
long memorySize = ((com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean()).getTotalPhysicalMemorySize();
For Ram Size , if you are using java 1.5
java.lang.management package
com.sun.management.OperatingSystemMXBean mxbean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
System.out.println(mxbean.getTotalPhysicalMemorySize() + " Bytes ");
import java.lang.management.*;
import java.io.*;
class max
{
public static void main(String... a)
{
long diskSize = new File("/").getTotalSpace();
String userName = System.getProperty("user.name");
long maxMemory = Runtime.getRuntime().maxMemory();
long memorySize = ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize();
System.out.println("Size of C:="+diskSize+" Bytes");
System.out.println("User Name="+userName);
System.out.println("RAM Size="+memorySize+" Bytes");
}
}
Have a look at this topic, which goes into detail of how to get OS information such as this.
For Ram capacity:
//this step get ram capacity
long ram= ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize();
long sizekb = ram /1000;
long sizemb = sizekb / 1000;
long sizegb = sizemb / 1000 ;
System.out.println("System Ram ="+sizegb+"gb");

Categories

Resources