What gives an increase in time by disabling garbage collection?

I read the code for the timeit module, and I noticed this segment:

gcold = gc.isenabled() gc.disable() timing = self.inner(it, self.timer) if gcold: gc.enable() 

It simply stores the garbage collection state (on or off) and then disables it. The inner function executes the execution time of the statement. He then returns the garbage collector to its previous state.

So I wonder what that point is. If the code being tested works as a garbage collector, should this not affect the testing? What am I missing?

+4
source share
2 answers

The nature of garbage collection is that its frequency and duration are somewhat unpredictable. At least in terms of the performance of a specific piece of code, the garbage collector simply adds noise to the statistics.

From the point of view of the whole program, you are right that if your program is running on a system where the garbage collector is running, then yes, which should be taken into account when measuring the performance of a program. But this is usually not taken into account for individual functions.

+5
source

Is this code supposed to be written as follows?

 gcold = gc.isenabled() gc.disable() try: timing = self.inner(it, self.timer) finally: if gcold: gc.enable() 

Otherwise, garbage collection will remain disabled if the programmed code throws an exception.

I reported this to bugs.python.org and it was fixed in Python 2.7.3 and 3.2.2.

+3
source

Source: https://habr.com/ru/post/1333258/


All Articles