Coding with Revit API: tips to reduce memory use?

半腔热情 提交于 2019-12-04 15:14:20

Basics:

Okay let's talk about a few important points here:

  • You're running scripts under IronPython which is an implementation of python in C# language
  • C# Language uses Garbage Collectors to collect unused memory.
  • Garbage Collector (GC) is a piece of program that is executed at intervals to collect the unused elements. It uses a series of techniques to group and categorize the target memory areas for later collection.
  • Your main program is halted by the operating system to allow the GC to collect memory. This means that if the GC needs more time to do its job at each interval, your program will get slow and you'll experience some lag.

Issue:

Now to the heart of this issue: python is an object-oriented programming language at heart and IronPython creates objects (Similar to Elements in Revit in concept) for everything, from your variables to methods of a class to functions and everything else. This means that all these objects need to be collected when they're not used anymore.

When using python as a scripting language for a program, there is generally one single python Engine that executes all user inputs.

However Revit does not have a command prompt and an associated python engine. So every time you run a script in Revit, a new engine is created that executes the program and dies at the end.

This dramatically increases the amount of unused memory for the GC to collect.

Solution:

I'm the creator and maintainer of pyRevit and this issue was resolved in pyRevit v4.2

The solution was to set LightweightScopes = true when creating the IronPython engine and this will force the engine to create smaller objects. This dramatically decreased the memory used by IronPython and increased the amount of time until the user experiences Revit performance degradation.

Sorry i can't comment with a low reputation, i use another way to reduce memory, it's less pretty than the LightweightScopes trick, but it works for one-time cleanup after expensive operations :

import gc

my_object = some_huge_object

# [operation]

del my_object    # or my_object = [] does the job for a list or dict
gc.collect()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!