1111import sys
1212import time
1313import warnings
14+ from pathlib import Path
1415from typing import TYPE_CHECKING , Any , Callable
1516from unittest import TestCase
1617
@@ -37,14 +38,39 @@ class UnexpectedError(Exception):
3738 pass
3839
3940
40- if platform .system () == "Linux" or platform . system () == "Darwin" :
41+ if platform .system () == "Linux" :
4142 import resource
4243
44+ # We set the memory limit to 85% of total system memory + swap when swap exists
45+ swap_file_path = Path ("/proc/swaps" )
46+ swap_exists = swap_file_path .is_file ()
47+ swap_size = 0
48+
49+ if swap_exists :
50+ with swap_file_path .open ("r" ) as f :
51+ swap_lines = f .readlines ()
52+ swap_exists = len (swap_lines ) > 1 # First line is header
53+
54+ if swap_exists :
55+ # Parse swap size from lines after header
56+ for line in swap_lines [1 :]:
57+ parts = line .split ()
58+ if len (parts ) >= 3 :
59+ # Swap size is in KB in the 3rd column
60+ try :
61+ swap_size += int (parts [2 ]) * 1024 # Convert KB to bytes
62+ except (ValueError , IndexError ):
63+ pass
64+
4365 # Get total system memory
44- total_memory = os .sysconf ("SC_PAGE_SIZE" ) * os .sysconf (
45- "SC_PHYS_PAGES"
46- ) # Set memory limit to 80% of total system memory
47- memory_limit = int (total_memory * 0.8 )
66+ total_memory = os .sysconf ("SC_PAGE_SIZE" ) * os .sysconf ("SC_PHYS_PAGES" )
67+
68+ # Add swap to total available memory if swap exists
69+ if swap_exists :
70+ total_memory += swap_size
71+
72+ # Set the memory limit to 85% of total memory (RAM plus swap)
73+ memory_limit = int (total_memory * 0.85 )
4874
4975 # Set both soft and hard limits
5076 resource .setrlimit (resource .RLIMIT_AS , (memory_limit , memory_limit ))
0 commit comments