Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to track the number of times a function is called?

Tags:

python

So i'm trying to make a function that keeps track how many times a method is called. for example:

a = [1,2,3,4] a.pop() 

i want to know how many times a.pop() was called so far so for this example, i would get 1. Is there a way to do this?

like image 956
user3050527 Avatar asked Feb 12 '14 01:02

user3050527


People also ask

How do you find out how many times a function is called?

To count how many times a function has been called, declare a count variable outside of the function, setting it to 0 . Inside of the body of the function reassign the variable incrementing it by 1 . The count variable will store the number of function invocations.

How do you keep track of how many times a function is called in Python?

You could use a decorator that tracks how many times the function is called. Since list is a built-in, you can't decorate or replace its pop method so you'd have to use your own list class, for example. Show activity on this post.

How do you count the number of times a function is called in C#?

You could use the Performance Profiler in Visual Studio (Analyze > Performance Profiler...). In Available Tools, check Performance Wizard. Start (choose Instrumentation method).


2 Answers

This doesn't work for builtin functions, but an interesting approach would be:

def myfunction():     myfunction.counter += 1 myfunction.counter = 0 

You're giving the function an attribute, so every call that attribute is updated. No global variables needed.

Built-ins are read-only. They cannot be modified.

like image 81
mhlester Avatar answered Nov 08 '22 08:11

mhlester


You could use a decorator that tracks how many times the function is called. Since list is a built-in, you can't decorate or replace its pop method so you'd have to use your own list class, for example.

def counted(f):     def wrapped(*args, **kwargs):         wrapped.calls += 1         return f(*args, **kwargs)     wrapped.calls = 0     return wrapped  class MyList(list):     @counted     def pop(self, *args, **kwargs):         return list.pop(self, *args, **kwargs)  x = MyList([1, 2, 3, 4, 5]) for i in range(3):     x.pop()  print x.pop.calls # prints 3 
like image 42
FogleBird Avatar answered Nov 08 '22 09:11

FogleBird