On this page
  1. resource
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Portable Peak Resident Memory (ru_maxrss) Helper
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

resource

Prev: reprlib | Up: stdlib_module | Next: rlcompleter
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — resource
Tags: #public #python3 #stdlib


Import

import resource

Overview

POSIX process resource usage and soft/hard limit controls (getrusage, getrlimit, setrlimit, RLIMIT_NOFILE, RLIMIT_CPU, RLIMIT_AS). Reach for resource to measure peak memory (ru_maxrss) and CPU time in benchmarks, or to enforce OS-level ceilings on worker subprocesses.

Quick Start

import resource

usage = resource.getrusage(resource.RUSAGE_SELF)
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
assert usage.ru_utime >= 0.0 and soft > 0

Implementation Walkthrough

1. Portable Peak Resident Memory (ru_maxrss) Helper

Note that macOS reports ru_maxrss in bytes, while Linux reports it in kilobytes:

import resource
import sys

def peak_rss_mib() -> float:
    rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    divisor = (1024 * 1024) if sys.platform == "darwin" else 1024
    return rss / divisor

assert peak_rss_mib() > 0.0

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes