Python profiling with PyCharm Community Edition

 

Before we start, if you don`t know what is profiling read this Wikipedia article! In my opinion profiling should be a part of every development/build process! Whether the responsibility lies with QA or development. Python profiler are supported only in PyCharm Professional Edition. This article show you the possibilities for the community edition.

Preparation

  • PyCharm installed
  • Virtualenv or similar installed (optional)
  • PyCharm BashSupport Plugin installed

The easiest Profiler

With Unix/Linux time command you have allready a simple profiler! Time writes a message to standard output. Here you will find some information on Stackoverflow.

1

2

3

4

5

6

7

8

9

10

11

12

#!/usr/bin/env python

# -*- coding: utf-8 -*-

 

 

def hello_world():

 

    for i in range(1, 5):

        print '%d Hello world from python...' % i

 

 

if __name__ == '__main__':

    hello_world()

With BashSupport Plugin we can setup the “Run/Debug Configuration” like:

Python profiling with PyCharm Community Edition_第1张图片

Better informations

But now we need better information. For this we use cProfile, cprofilev and snakeviz.

1

2

3

4

5

6

7

# cProfile is part of standard python library

 

# install snakeviz

$ pip install snakeviz

 

# install cprofildev

$ pip install cprofilev

“Run/Debug Configuration” example

Python profiling with PyCharm Community Edition_第2张图片

Now will store the results into a file

cProfile store output

With snakeviz you can open the profile in browser:

1

$ snakeviz output.prof

The other option is to use cprofilev:

cprofilev

Even more information

If that was not enough,… we install some more libraries.

1

2

3

4

5

6

# install line_profiler

$ pip install line_profiler

 

# install memory_profiler and psutil

$ pip install memory_profiler

$ pip install psutil

Now we need to change the example code. We add the decorator…

1

2

3

4

5

6

7

8

9

10

11

12

13

#!/usr/bin/env python

# -*- coding: utf-8 -*-

 

 

@profile

def hello_world():

 

    for i in range(1, 5):

        print '%d Hello world from python...' % i

 

 

if __name__ == '__main__':

    hello_world()

the line_profiler configuration

Python profiling with PyCharm Community Edition_第3张图片

the memory_profiler

Python profiling with PyCharm Community Edition_第4张图片

All configurations could now startet via the “Run” button. There are even more Profiler that you can use with similar PyCharm.

转载于:https://my.oschina.net/u/2272631/blog/818508

你可能感兴趣的:(Python profiling with PyCharm Community Edition)