Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import cProfile in Python 3

I am trying to import the cProfile module into Python 3.3.0, but I got the following error:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    import cProfile
  File "/.../cProfile_try.py", line 12, in <module>
    help(cProfile.run)
AttributeError: 'module' object has no attribute 'run'

The complete code (cProfile_try.py) is as follows

import cProfile
help(cProfile.run)

L = list(range(10000000))
len(L)
# 10000000

def binary_search(L, v):
    """ (list, object) -> int

    Precondition: L is sorted from smallest to largest, and
    all the items in L can be compared to v.

    Return the index of the first occurrence of v in L, or
    return -1 if v is not in L.

    >>> binary_search([2, 3, 5, 7], 2)
    0
    >>> binary_search([2, 3, 5, 5], 5)
    2
    >>> binary_search([2, 3, 5, 7], 8)
    -1
    """

    b = 0
    e = len(L) - 1

    while b <= e:
        m = (b + e) // 2
        if L[m] < v:
            b = m + 1
        else:
            e = m - 1

    if b == len(L) or L[b] != v:
        return -1
    else:
        return b

cProfile.run('binary_search(L, 10000000)')
like image 614
alittleboy Avatar asked Apr 15 '13 02:04

alittleboy


People also ask

How do you use cProfile in Python 3?

The syntax is cProfile. run(statement, filename=None, sort=-1) . You can pass python code or a function name that you want to profile as a string to the statement argument. If you want to save the output in a file, it can be passed to the filename argument.

What is Python profiler?

Introduction to the profilers cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.


1 Answers

As noted in a comment, it is likely that there unexpectedly exists a file named profile.py, possibly in the current directory. This file is being unintentionally used by cProfile, thereby masking Python's profile module.

A suggested solution is:

mv profile.py profiler.py

Next, for good measure,

If using Python 3:

rm __pycache__/profile.*.pyc

If using Python 2:

rm profile.pyc
like image 136
Asclepius Avatar answered Oct 28 '22 16:10

Asclepius