Major programming languages and functions to check memory usage

VPS

We have compiled a list of major programming languages and functions to check the amount of memory used, including Python, Java, Node.js, and Ruby.

Modified at: 2023.2.23Posted at: 2023.2.21

Python

The psutil module can be used to get the memory usage of the current process.

import psutil
process = psutil.Process()
memory_info = process.memory_info().rss / 1024 / 1024 # Convert RSS (Resident Set Size) to MB
print("Memory usage: ", memory_info, "MB")

Java

You can use the totalMemory() and freeMemory() methods of the Runtime class to get the memory usage of the current process.

long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = totalMemory - freeMemory;
System.out.println("Memory usage: " + usedMemory + " bytes");

C++

In C++, memory usage can be obtained using the GlobalMemoryStatus() function in the Windows.h header file.

#include <windows.h>
MEMORYSTATUS memStatus;
memStatus.dwLength = sizeof(memStatus);
GlobalMemoryStatus(&memStatus);
DWORDLONG memoryUsed = memStatus.dwTotalPhys - memStatus.dwAvailPhys;
std::cout << "Memory usage: " << memoryUsed / 1024 << " KB" << std::endl;

JavaScript

The performance object can be used to get the memory usage of the current process.

let memoryUsage = window.performance.memory.usedJSHeapSize / 1024 / 1024;
console.log("Memory usage: ", memoryUsage, "MB");

Node.js

In Node.js, you can get the amount of memory used by a process with "process.memoryUsage()".

const used = process.memoryUsage();
for (let key in used) {
  console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`)
}

Ruby

Ruby has a standard library, objspace, to get memory usage. Use as follows.

require 'objspace'

obj_size = ObjectSpace.memsize_of(object)

Go Lang

Go Lang has a runtime package to get runtime metrics. Use the following.

import "runtime"

var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Alloc = %v MiB", m.Alloc / 1024 / 1024)

Categories related to this article

VPS

VPS servers are used for a variety of purposes. Here you can learn the basics of VPS and compare multiple VPS servers. Choose the VPS server that is best for you.