human
I am working on the file "Extra 1 - Comparing ML algorithms.ipynb".
The first task is:
Testing and collecting measurements
First, we define the Timer class (below, taken from this recipe) to measure the computing time of training and classification. Note that this class allows us to disable garbage collection between measurements for more consistent results.
Can you write Python code for it?
assistant
#Here is the Python code you requested.

import gc
import timeit

class Timer:
    def __init__(self, timer=None, disable_gc=False, verbose=True):
        if timer is None:
            timer = timeit.default_timer
        self.timer = timer
        self.disable_gc = disable_gc
        self.gc_state = None
        self.verbose = verbose
        self.start = self.end = self.interval = None
        
    def __enter__(self):
        if self.disable_gc:
            self.gc_state = gc.isenabled()
            gc.disable()
        self.start = self.timer()
        return self

    def __exit__(self, *args):
        self.end = self.timer()
        if self.disable_gc and self.gc_state:
            gc.enable()
            self.gc_state = None            
        self.interval = self.end - self.start
        if self.verbose:
            print('time taken: %f seconds' % self.interval)