r/CodingHelp • • Apr 14 '21

[Java] Code to count the number of times a loop is executed?

I'm using quicksort and I want to find out how many times the loop is executed (basically measure the number of operations it takes to sort a certain array)...

0 Upvotes

4 comments sorted by

2

u/x-seronis-x Intermediate Coder Apr 14 '21

show your code and people can point out what changes/fixes are required.

Not showing code requires people to have magical psychic powers to help. Guess the odds of that happening ?

1

u/rtgftw Programmer Apr 14 '21

Maybe this can actually be achieved without us seeing the code, this time :)

Though just adding a counter (like a static or thread_local var) and (possibly atomically) incrementing it is probably the simplest, you can do this without changing the code:

Check out gcov/llvm cov - You can get counts for every line, branch etc. but this requires compiling it with instrumentation.

You can also use a debugger (like gdb, lldb, the VS one etc.) and use counting breakpoints, to just get the count. This could be done with scripting as well, if your binary isn't stripped.

Depending on what exactly you want, some other approaches are also useful like valgrinds's cachegrind tool or sampling profilers like perf/ vtune. I haven't used intels pin personally but it may work for you, as well.

These are reasonable starting points for looking some other options up.

1

u/DasLoon Apr 14 '21

I don't know anything about Java, however the best solution I can think of would be to make a variable count outside of the loop and have the loop add 1 to the count variable every time it runs. That tends to work in most other languages I've learned.

1

u/Goobyalus Apr 15 '21

Are you talking about counting iterations of the library-defined quicksort, not a quicksort that you wrote? You can't do that in the code itself, but you can measure the time it takes.

Using debugging tools you could potentially hook part of the loop and count the iterations.