ansys / pytwin

Ansys Digital Twin repository
https://twin.docs.pyansys.com
MIT License
19 stars 7 forks source link

TwinModel instance keep allocating memory when used in a loop #128

Closed lboucin closed 11 months ago

lboucin commented 11 months ago

πŸ” Before submitting the issue

🐞 Description of the bug

When instantiating a TwinModel in a loop, the allocated memory keep increasing.

image

πŸ“ Steps to reproduce

import os import tracemalloc from pytwin import TwinModel

tracemalloc.start() snapshot = tracemalloc.take_snapshot()

twin_file = os.path.join("path_to_a_twin_model_with_tbrom.twin") for i in range(1, 100): twin_model = TwinModel(model_filepath=twin_file) snapshot2 = tracemalloc.take_snapshot() top_stats = snapshot2.compare_to(snapshot, 'lineno') stat_tbrom_read_basis = top_stats[0] print(stat_tbrom_read_basis)

πŸ’» Which operating system are you using?

Windows

πŸ“€ Which ANSYS version are you using?

NA

🐍 Which Python version are you using?

3.9

πŸ“¦ Installed packages

certifi==2023.7.22
charset-normalizer==3.3.2
colorama==0.4.6
coverage==7.3.2
cycler==0.11.0
exceptiongroup==1.1.3    
fonttools==4.38.0        
idna==3.4
imageio==2.31.2
iniconfig==2.0.0
kiwisolver==1.4.5        
matplotlib==3.5.3        
numpy==1.21.1
packaging==23.2
pandas==1.3.5
Pillow==9.5.0
platformdirs==4.0.0      
pluggy==1.3.0
pooch==1.8.0
pyparsing==3.1.1
pytest==7.4.3
pytest-cov==4.1.0
python-dateutil==2.8.2
-e git+https://github.com/ansys/pytwin@16cf78a84ed27a2881d0c7781a8afe66750a76e9#egg=pytwin
pytz==2023.3.post1
pyvista==0.38.6
pywin32==306
requests==2.31.0
scooby==0.7.3
six==1.16.0
tomli==2.0.1
tqdm==4.66.1
urllib3==2.0.7
vtk==9.3.0
lboucin commented 11 months ago

Adding the following statement twin_model._tbroms = None at the end of the loop solve the issue, see below: image

lboucin commented 11 months ago

Investigations: We are registering the __del__ method of the TwinModel with the atexit module in order to avoid the settings module tries to delete pytwin temp folder of the process before the log file of the TwinRuntime object owned by the TwinModel has been closed. This has a side effect which is that a TwinModel instance is referenced by the atexit module and thus preventing the garbage collector to collect and free the TwinModel at the end of the loop.

lboucin commented 11 months ago

@chrpetre see proposed solution in PR #130