11
11
import sys
12
12
import time
13
13
import warnings
14
+ from pathlib import Path
14
15
from typing import TYPE_CHECKING , Any , Callable
15
16
from unittest import TestCase
16
17
@@ -37,14 +38,39 @@ class UnexpectedError(Exception):
37
38
pass
38
39
39
40
40
- if platform .system () == "Linux" or platform . system () == "Darwin" :
41
+ if platform .system () == "Linux" :
41
42
import resource
42
43
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
+
43
65
# 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 )
48
74
49
75
# Set both soft and hard limits
50
76
resource .setrlimit (resource .RLIMIT_AS , (memory_limit , memory_limit ))
0 commit comments