简体   繁体   中英

cProfiling a module with relative imports

I have these files in mymodule

mymodule
├── config.py
├── __init__.py
└── lib.py

With this simple content:

# config.py
NAME = "Julius Cesar"

# lib.py
from .config import NAME

def get_name():
    return NAME

I can run it (and nothing happens) with python -m mymodule.lib

But I can not profile it:

» python -m cProfile mymodule/lib.py 
         2 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 lib.py:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/cProfile.py", line 199, in <module>
    main()
  File "/usr/lib/python2.7/cProfile.py", line 192, in main
    runctx(code, globs, None, options.outfile, options.sort)
  File "/usr/lib/python2.7/cProfile.py", line 49, in runctx
    prof = prof.runctx(statement, globals, locals)
  File "/usr/lib/python2.7/cProfile.py", line 140, in runctx
    exec cmd in globals, locals
  File "mymodule/lib.py", line 1, in <module>
    from .config import NAME
ValueError: Attempted relative import in non-package

So, how can I cProfile a library? Since the library is not doing anything, only the import of the lib module would be profiled, but that is good enough for me. I do not want at this stage to profile all function calls, just the importing of the module.

How can I do this with cProfile for modules with relative imports, avoiding the ValueError s?

I hope I got this correct, but you can use the cProfile API like so:

» python
>>> import cProfile
>>> cProfile.run('import mylib.lib')
  511 function calls (500 primitive calls) in 0.002 seconds
  Ordered by: standard name
  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   3    0.000    0.000    0.000    0.000 <frozen importlib._bootstrap>:119(release)
   ...
>>>

Or you can do it in one line like python -c "import cProfile; cProfile.run('import mylib.lib')" .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM