Does anyone have a meaningfull example of the use of the Profiler included in Python?

Recommended Answers

All 2 Replies

I was looking for a halfway decent example code, but when you also asked for list comprehension, a light went up, and I combined the two questions:

# using the module profile to profile a function or a statement

import profile

#help('profile.run')

def evenList1():
    """returns a list of even numbers from 0 to 99998 using append in a loop
    the 50000 calls to append() consume much CPU time
    """
    L1 = []
    for x in range(100000):
        if x % 2 == 0:
            L1.append(x)
    return L1

def evenList2():
    """returns a list of even numbers from 0 to 99998 using list comprehension
    much faster in CPU time than the standard loop with append()
    """
    L2 = [x for x in range(100000) if x % 2 == 0]
    return L2
        

# test first 30 elements
print evenList1()[0:30]
print evenList2()[0:30]

print
print "Profile of evenList1(), check the time consumed by the many append() calls:"
print "(ignore time consumed by the profiler itself)\n"
profile.run('evenList1()')

print "Profile of evenList2():"
print "(ignore time consumed by the profiler itself)\n"
profile.run('evenList2()')

I hope this will show you how to use the Python profile module and give you some insight into list comprehension.

It works and gives much information, thank you muchly!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.