-1

I am trying to use timeit to get the run time of one of the function in the with two arguments, but I keep getting error: cannot import name make_heap() class queueHeap(): def make_heap(self, alist): i = len(alist)//2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i > 0): self.swapDown(i) i = i - 1

for num in range(1, 100, 10) :
        L = []
        binaryHeap = queueHeap()
        for i in range(1, num):
                randomElement = random.randint(1, 100)
                L.append(randomElement)
                time_MakeHeap = timeit.Timer('make_heap(self, L)', 'from __main__ import make_heap, self, L')
                print("n=%s: %s" % (num,  time_MakeHeap.timeit(1)))
Joe
  • 1
  • 2
  • the class is queueHeap(): – Joe Feb 12 '15 at 07:42
  • Please fix the code formatting in the question. As it stands it's completely impossible to understand what it does, since all indentation is messed up and part of it isn't in a code block. – Bakuriu Feb 12 '15 at 08:17

1 Answers1

0

The problem is that __main__ refers to the current module, not the current scope.

For example if you have a testing.py file with:

class Test:
    def method(self):
        import __main__
        print(vars(__main__))

Test().method()

The output of running it is:

$python3 testing.py 
{'__file__': 'testing.py', '__cached__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x7f5e8a027518>, '__doc__': None, '__spec__': None, '__name__': '__main__', '__package__': None, 'Test': <class '__main__.Test'>}

Note:

  1. self isn't in the dictionary returned
  2. method isn't either
  3. Only module-level variables are in there

so you cannot access self and method like that. In fact, the whole thing seems really bad design. Why do you want to profile a class inside one of its methods? Just use an instance:

my_instance = MyClass()
result = timeit.Timer('my_instance.the_method()', 'from __main__ import my_instance').timeit(1)
Bakuriu
  • 98,325
  • 22
  • 197
  • 231