googlecolab / colabtools

Python libraries for Google Colaboratory
Apache License 2.0
2.2k stars 722 forks source link

%timeit doesn't grab variables in function scope #1034

Open gabrieldemarmiesse opened 4 years ago

gabrieldemarmiesse commented 4 years ago

Bug report for Colab: http://colab.research.google.com/.

For questions about colab usage, please use stackoverflow.

get_times()


NameError Traceback (most recent call last)

in () 3 get_ipython().magic('timeit a + 1') 4 ----> 5 get_times() 5 frames in get_times() 1 def get_times(): 2 a = 8 ----> 3 get_ipython().magic('timeit a + 1') 4 5 get_times() /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in magic(self, arg_s) 2158 magic_name, _, magic_arg_s = arg_s.partition(' ') 2159 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) -> 2160 return self.run_line_magic(magic_name, magic_arg_s) 2161 2162 #------------------------------------------------------------------------- /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line) 2079 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2080 with self.builtin_trap: -> 2081 result = fn(*args,**kwargs) 2082 return result 2083 in timeit(self, line, cell) /usr/local/lib/python3.6/dist-packages/IPython/core/magic.py in (f, *a, **k) 186 # but it's overkill for just that one bit of state. 187 def magic_deco(arg): --> 188 call = lambda f, *a, **k: f(*a, **k) 189 190 if callable(arg): /usr/local/lib/python3.6/dist-packages/IPython/core/magics/execution.py in timeit(self, line, cell) 1055 number = 1 1056 for _ in range(1, 10): -> 1057 time_number = timer.timeit(number) 1058 worst_tuning = max(worst_tuning, time_number / number) 1059 if time_number >= 0.2: /usr/local/lib/python3.6/dist-packages/IPython/core/magics/execution.py in timeit(self, number) 137 gc.disable() 138 try: --> 139 timing = self.inner(it, self.timer) 140 finally: 141 if gcold: in inner(_it, _timer) NameError: name 'a' is not defined ``` - Describe the expected behavior: In a local jupyter notebook: ``` 37.4 ns ± 0.283 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` - The web browser you are using (Chrome, Firefox, Safari, etc.): Chrome - Link to self-contained notebook that reproduces this issue (click the *Share* button, then *Get Shareable Link*): https://colab.research.google.com/drive/1rBpMpr-VS2fD8LKyA5BmUmxZjP6nLlV0
colaboratory-team commented 4 years ago

This is a bug in IPython that was fixed in version 6.2 (see https://github.com/ipython/ipython/commit/6d2b31146a00a1fbe8a36a8609daa0e9a8b13018). Colab currently uses IPython 5.5.

As a workaround, you can declare the variable globally:

def get_times():
    global a
    a = 8
    %timeit a + 1

get_times()
10000000 loops, best of 3: 32.9 ns per loop
gabrieldemarmiesse commented 4 years ago

Thank you!

johnsmith3000 commented 3 years ago

or you can run in colab cell: !pip install --upgrade IPython