Created
July 10, 2021 22:46
-
-
Save penut85420/d66b38211eb34308d91bddcb885bca04 to your computer and use it in GitHub Desktop.
A python demo script of memory information and garbage collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import gc | |
import time | |
import psutil | |
def get_process_memory(): | |
process = psutil.Process(os.getpid()) | |
mem_info = process.memory_info() | |
return mem_info.rss / 1024 / 1024 | |
class M: | |
def __enter__(self): | |
self.m = get_process_memory() | |
def __exit__(self, *args): | |
n = get_process_memory() | |
print(f'{self.m:.2f} {n:.2f} ({n - self.m:.2f})') | |
def main(): | |
size = 10000 | |
with M(): | |
arr = [[i for i in range(size)] for j in range(size)] | |
with M(): | |
del arr | |
with M(): | |
gc.collect() | |
with M(): | |
time.sleep(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment