0

I'm very unfamiliar with Python 2.x and I have some inherited code in many files where I need to count how many times some particular functions are called (to solve a particular problem).

To show what I mean, in another simple language I would do this

Add at the beginning of the code

counter_funcA = 0
counter_funcB = 0
...

In the beginning of function A

counter_funcA += 1

In the beginning of function B

counter_funcB += 1

And so on...

And at the end

print counter_funcA
...

So how would a python expert do this in a nice way?

I guess the operation += is quite atomic -- so there will not be any concurrency issues?

martineau
  • 119,623
  • 25
  • 170
  • 301
FORTRAN
  • 567
  • 1
  • 6
  • 13
  • 1
    "I need to count how many times some particular functions are called (to solve a particular problem)" -- What kind of problem are you trying to solve? Is this for performance debugging? If it is, can I recommend that you use [python's profiler](https://docs.python.org/2/library/profile.html)? If it isn't, then it's possible that there are better solutions than global state (e.g. a decorator that manages the counts, etc.). Can you tell us more about the problem you're actually trying to solve? – mgilson Apr 26 '17 at 06:43
  • I really really like this answer to the same question: http://stackoverflow.com/a/21717084/1870832 – Max Power Apr 26 '17 at 06:51
  • The decorator portion of [this answer](http://stackoverflow.com/a/21717396/355230) to the same question is better IMO. – martineau Apr 26 '17 at 07:11
  • `+=` is not atomic, see [this answer](http://stackoverflow.com/a/1718843/7486016) – B. Barbieri Apr 26 '17 at 11:49

0 Answers0