Saturday, April 11, 2026

Check RAM (Memory) Usage Using Python: A Complete Guide

 

Check RAM (Memory) Usage Using Python: A Complete Guide

Monitoring system memory (RAM) is an essential task for developers, system administrators, and anyone working with performance-sensitive applications. High memory usage can slow down programs, cause crashes, or impact overall system performance. Fortunately, Python provides simple and powerful ways to check RAM usage with just a few lines of code.

In this blog, you’ll learn how to monitor memory usage in Python using different methods, from basic built-in tools to advanced libraries.

1. Why Monitor RAM Usage?

Before diving into code, it’s important to understand why memory monitoring matters:

  • Performance optimization: Identify memory-heavy processes
  • Debugging: Detect memory leaks
  • System monitoring: Keep track of overall usage
  • Efficient resource usage: Prevent crashes in large applications

2. Understanding RAM Usage

RAM (Random Access Memory) stores data temporarily while your system is running. When you run a Python program, it consumes a portion of RAM.

Key terms:

  • Total memory – Total RAM available
  • Used memory – Memory currently in use
  • Free memory – Available RAM

3. Using psutil Library (Best Method)

The most popular way to check RAM usage in Python is by using the psutil library.

Installation

pip install psutil

Check Overall System Memory

import psutil

memory = psutil.virtual_memory()

print("Total:", memory.total)
print("Available:", memory.available)
print("Used:", memory.used)
print("Percentage:", memory.percent)

Output Example

Total: 8589934592
Available: 4294967296
Used: 4294967296
Percentage: 50.0

Convert Bytes to GB

def to_gb(bytes_value):
    return bytes_value / (1024 ** 3)

print("Total RAM:", to_gb(memory.total), "GB")

4. Check Memory Usage of a Specific Process

You can also monitor how much RAM a particular Python program is using.

import psutil
import os

process = psutil.Process(os.getpid())
print("Memory Used:", process.memory_info().rss)

This returns memory usage in bytes for the current process.

5. Using os and resource (Linux/Mac)

For Unix-based systems, you can use built-in modules.

import resource

usage = resource.getrusage(resource.RUSAGE_SELF)
print("Memory usage:", usage.ru_maxrss)

Note: This method may not work on Windows.

6. Using tracemalloc for Memory Tracking

Python also provides a built-in module called tracemalloc for tracking memory allocations.

import tracemalloc

tracemalloc.start()

# Example code
a = [i for i in range(100000)]

current, peak = tracemalloc.get_traced_memory()

print("Current memory:", current)
print("Peak memory:", peak)

tracemalloc.stop()

7. Monitoring Memory in Real-Time

You can continuously track RAM usage using a loop:

import psutil
import time

while True:
    memory = psutil.virtual_memory()
    print(f"RAM Usage: {memory.percent}%")
    time.sleep(1)

This is useful for real-time monitoring tools.

8. Creating a Simple RAM Monitor Script

Here’s a simple script combining everything:

import psutil

def check_ram():
    memory = psutil.virtual_memory()
    
    print("Total RAM:", round(memory.total / (1024**3), 2), "GB")
    print("Used RAM:", round(memory.used / (1024**3), 2), "GB")
    print("Free RAM:", round(memory.available / (1024**3), 2), "GB")
    print("Usage:", memory.percent, "%")

check_ram()

9. Use Cases in Real Projects

1. Web Applications

Monitor memory usage to prevent server crashes.

2. Data Science

Track RAM while handling large datasets.

3. Automation Scripts

Ensure scripts don’t consume excessive resources.

4. Game Development

Optimize performance by managing memory efficiently.

10. Performance Tips

  • Avoid storing large unnecessary data in memory
  • Use generators instead of lists
  • Free unused variables using del
  • Use memory profiling tools

11. Common Issues and Solutions

High Memory Usage

  • Optimize data structures
  • Use efficient algorithms

Memory Leaks

  • Check for unused references
  • Use tracemalloc to debug

Slow Performance

  • Monitor both CPU and RAM usage
  • Optimize loops and logic

12. Comparison of Methods

Method Ease of Use Platform Support Best For
psutil ⭐⭐⭐⭐⭐ All platforms General use
resource ⭐⭐ Linux/Mac Basic usage
tracemalloc ⭐⭐⭐ All platforms Debugging

Conclusion

Checking RAM usage using Python is simple yet extremely powerful. Whether you're building small scripts or large-scale applications, monitoring memory helps you write efficient and stable programs.

The psutil library is the easiest and most versatile option, while tools like tracemalloc provide deeper insights into memory allocation. By combining these techniques, you can ensure your applications run smoothly without consuming unnecessary resources.

As you continue your Python journey, integrating memory monitoring into your workflow will help you build faster, smarter, and more reliable software.

Monitor Network I/O (Upload/Download) in Python: A Complete Guide

 

Monitor Network I/O (Upload/Download) in Python: A Complete Guide

In modern computing, monitoring network activity is just as important as tracking CPU or memory usage. Whether you are building a system monitoring tool, optimizing applications, or simply curious about your internet usage, Python provides powerful ways to track network input/output (I/O) — that is, data being uploaded and downloaded.

In this blog, you’ll learn how to monitor network I/O in Python using practical examples, tools, and best practices.

1. What is Network I/O?

Network I/O refers to the amount of data transferred over a network interface.

  • Download (Received) → Data coming into your system
  • Upload (Sent) → Data leaving your system

This data is usually measured in bytes, kilobytes (KB), megabytes (MB), or gigabytes (GB).

2. Why Monitor Network Usage?

Monitoring network I/O is useful for:

  • Tracking internet usage
  • Detecting unusual activity
  • Optimizing applications
  • Building monitoring dashboards
  • Troubleshooting slow networks

3. Using psutil to Monitor Network I/O

The easiest and most popular way to monitor network usage in Python is by using the psutil library.

Installation

pip install psutil

4. Basic Network I/O Monitoring

import psutil

net = psutil.net_io_counters()

print("Bytes Sent:", net.bytes_sent)
print("Bytes Received:", net.bytes_recv)

This gives total data sent and received since the system started.

5. Converting Bytes to MB

def bytes_to_mb(bytes_value):
    return bytes_value / (1024 * 1024)

print("Upload:", bytes_to_mb(net.bytes_sent), "MB")
print("Download:", bytes_to_mb(net.bytes_recv), "MB")

6. Real-Time Network Speed Monitoring

To monitor upload and download speed, you need to calculate the difference over time.

import psutil
import time

old_value = psutil.net_io_counters()

while True:
    time.sleep(1)
    new_value = psutil.net_io_counters()
    
    upload_speed = new_value.bytes_sent - old_value.bytes_sent
    download_speed = new_value.bytes_recv - old_value.bytes_recv
    
    print(f"Upload: {upload_speed / 1024:.2f} KB/s | Download: {download_speed / 1024:.2f} KB/s")
    
    old_value = new_value

This script updates every second and shows live network speed.

7. Monitor Specific Network Interfaces

If your system has multiple interfaces (Wi-Fi, Ethernet), you can monitor them separately:

net = psutil.net_io_counters(pernic=True)

for interface, stats in net.items():
    print(interface, stats.bytes_sent, stats.bytes_recv)

8. Building a Simple Network Monitor Tool

Here’s a clean and reusable script:

import psutil
import time

def monitor_network():
    old = psutil.net_io_counters()
    
    while True:
        time.sleep(1)
        new = psutil.net_io_counters()
        
        upload = (new.bytes_sent - old.bytes_sent) / 1024
        download = (new.bytes_recv - old.bytes_recv) / 1024
        
        print(f"Upload: {upload:.2f} KB/s | Download: {download:.2f} KB/s")
        
        old = new

monitor_network()

9. Use Cases in Real Projects

1. System Monitoring Dashboard

Track network performance along with CPU and RAM.

2. Data Usage Tracker

Measure how much internet you consume daily or monthly.

3. Cybersecurity

Detect unusual spikes in upload/download activity.

4. Server Monitoring

Ensure servers are handling traffic efficiently.

10. Improving Your Network Monitor

You can enhance your script by:

  • Converting speeds to MB/s or GB/s
  • Logging data to a file
  • Displaying graphs using libraries like matplotlib
  • Adding alerts for high usage

11. Performance Tips

  • Avoid very short intervals (like milliseconds)
  • Use efficient loops
  • Combine with threading for better performance
  • Monitor only required interfaces

12. Common Issues and Fixes

Values Not Changing

Ensure there is active network usage.

Incorrect Speed Calculation

Make sure the time interval is consistent.

High CPU Usage

Increase sleep time in loops.

13. Difference Between Total and Real-Time Usage

Type Description
Total Usage Data transferred since system start
Real-Time Speed Data transferred per second

Both are useful depending on your use case.

Conclusion

Monitoring network I/O in Python is simple yet extremely powerful. With just a few lines of code using psutil, you can track total data usage, measure real-time upload/download speed, and even build your own network monitoring tool.

Whether you're a developer optimizing applications, a student learning system programming, or a professional managing servers, understanding network usage gives you better control over performance and security.

Start with basic scripts, experiment with real-time monitoring, and gradually build advanced tools like dashboards or alert systems. With Python, you have everything you need to monitor and manage network activity efficiently.

Wednesday, April 8, 2026

Understanding the len() Function in Python

 


Understanding the len() Function in Python

https://technologiesinternetz.blogspot.com


Python is one of the most beginner-friendly programming languages, known for its simple syntax and powerful built-in functions. One such essential function is len(). Whether you are working with strings, lists, or other data types, the len() function helps you quickly determine the size of an object.

In this blog, we will explore what len() is, how it works, and where it is commonly used.

What is the len() Function?

The len() function in Python is used to find the number of items in an object. These objects can include:

  • Strings
  • Lists
  • Tuples
  • Dictionaries
  • Sets

In simple words, len() tells you how many elements are inside something.

Syntax of len()

len(object)
  • object can be any sequence or collection.
  • The function returns an integer value representing the length.

Using len() with Different Data Types

1. Length of a String

Strings are sequences of characters. The len() function counts all characters, including spaces.

text = "Hello World"
print(len(text))

Output:

11

2. Length of a List

Lists store multiple items. len() returns the total number of elements.

numbers = [10, 20, 30, 40]
print(len(numbers))

Output:

4

3. Length of a Tuple

Tuples are similar to lists but immutable.

data = (1, 2, 3)
print(len(data))

Output:

3

4. Length of a Dictionary

In dictionaries, len() counts the number of key-value pairs.

student = {"name": "Rahul", "age": 16, "grade": 10}
print(len(student))

Output:

3

5. Length of a Set

Sets store unique elements only.

items = {1, 2, 3, 3, 4}
print(len(items))

Output:

4

Why is len() Important?

The len() function is very useful in programming. Here are some common uses:

1. Loop Control

You can use len() to control loops.

fruits = ["apple", "banana", "mango"]

for i in range(len(fruits)):
    print(fruits[i])

2. Validation

Check if input is empty or not.

password = "abc123"

if len(password) < 6:
    print("Password too short")

3. Data Analysis

When working with data, knowing the size helps in processing.

Important Points to Remember

  • len() always returns an integer.
  • It works only with objects that have a defined length.
  • It does not work with numbers like int or float.

Example:

print(len(100))

Error: TypeError

Common Mistakes

1. Using len() on Numbers

num = 1234
print(len(num))  # Error

 Fix:

print(len(str(num)))

2. Confusing Characters with Words

sentence = "Python is fun"
print(len(sentence))

This counts characters, not words.

Conclusion

The len() function is a simple yet powerful tool in Python. It helps programmers understand the size of different data structures and is widely used in loops, conditions, and data handling.

If you are starting your Python journey, mastering len() will make your coding much easier and more efficient.

Tuesday, April 7, 2026

How AI is Changing Eye Treatment and Surgery: A New Vision for Healthcare

 


 How AI is Changing Eye Treatment and Surgery: A New Vision for Healthcare

https://technologiesinternetz.blogspot.com


Artificial Intelligence (AI) is rapidly transforming healthcare, and one of the most exciting areas of impact is eye care and ophthalmology. From early disease detection to robotic-assisted surgeries, AI is helping doctors diagnose faster, treat more accurately, and improve patient outcomes.

In this blog, we’ll explore how AI is reshaping eye treatment and surgery, making vision care smarter, safer, and more accessible.

 The Role of AI in Eye Care

AI uses advanced algorithms and machine learning to analyze medical data such as eye scans, images, and patient history. These systems can detect patterns that may be difficult for the human eye to notice.

 The result? Faster diagnosis, fewer errors, and more personalized treatments.

 1. Early Detection of Eye Diseases

One of the biggest advantages of AI is its ability to detect diseases at an early stage.

 Common Conditions Detected by AI

  • Diabetic retinopathy
  • Glaucoma
  • Age-related macular degeneration (AMD)

 How It Works

AI analyzes retinal images and scans to identify tiny abnormalities. Early detection allows doctors to begin treatment before the disease progresses.

 This can prevent permanent vision loss in many cases.

 2. Accurate Diagnosis with Imaging

AI-powered systems can process thousands of eye scans in seconds.

 Technologies Used

  • Optical Coherence Tomography (OCT)
  • Fundus photography
  • Deep learning models

 Benefits

  • Reduces diagnostic errors
  • Provides second opinions instantly
  • Helps doctors make confident decisions

 3. Personalized Treatment Plans

Every patient’s eye condition is different. AI helps create customized treatment plans.

 How AI Helps

  • Analyzes patient history
  • Predicts disease progression
  • Suggests optimal treatment strategies

 This leads to more effective and targeted care.

 4. AI in Eye Surgery

AI is revolutionizing surgical procedures by increasing precision and safety.

 Key Innovations

  • Robotic-assisted eye surgery
  • Laser-guided procedures
  • Real-time surgical monitoring

 Example

In cataract surgery, AI can guide laser systems to make precise incisions, improving outcomes and reducing recovery time.

 5. Faster and Safer Surgeries

AI reduces human error during complex procedures.

 Advantages

  • High precision
  • Reduced complications
  • Shorter surgery time

 Patients experience faster recovery and better results.

 6. Remote Eye Care (Tele-Ophthalmology)

AI enables remote diagnosis and consultation.

 How It Works

  • Patients upload eye images
  • AI analyzes the data
  • Doctors review results remotely

 This is especially useful in rural and underserved areas.

 7. AI-Powered Eye Screening Apps

Smartphone apps powered by AI can now perform basic eye tests.

 Features

  • Vision screening
  • Disease detection alerts
  • Eye health monitoring

 These tools make eye care more accessible to everyone.

 8. Predicting Future Eye Problems

AI can predict the risk of developing eye diseases.

 How It Helps

  • Identifies high-risk patients
  • Recommends preventive measures
  • Improves long-term eye health

 Challenges and Limitations

While AI offers many benefits, there are still challenges:

  • Data privacy concerns
  • High implementation costs
  • Need for human oversight
  • Limited access in some regions

 AI supports doctors—it does not replace them.

 The Future of AI in Eye Care

The future looks promising, with ongoing advancements such as:

  • Fully automated diagnosis systems
  • Advanced robotic surgeries
  • Integration with wearable devices
  • Real-time health monitoring

 Real-World Impact

AI is already making a difference:

  • Faster diagnosis in hospitals
  • Reduced blindness rates
  • Improved surgical success
  • Better access to eye care globally

 Final Thoughts

AI is giving healthcare professionals a powerful new tool to protect and restore vision. By combining human expertise with machine intelligence, eye treatment and surgery are becoming more precise, efficient, and accessible.

As technology continues to evolve, AI will play an even bigger role in helping people see the world more clearly—literally and figuratively.

Check RAM (Memory) Usage Using Python: A Complete Guide

  Check RAM (Memory) Usage Using Python: A Complete Guide Monitoring system memory (RAM) is an essential task for developers, system admini...