Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count operations in C++?

How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.

like image 710
MrDatabase Avatar asked Nov 01 '08 08:11

MrDatabase


People also ask

How do you count number of operations?

Approach: Count the number of times all the operations can be performed on the number k without actually reducing it to get the result. Then update count = times * n where n is the number of operations. Now, for the remaining operations perform each of the operation one by one and increment count.

What is Operation count?

The operation-count method of estimating time complexity omits accounting for the time spent on all but the chosen operations. In the step-count method, we attempt to account for the time spent in all parts of the algorithm. As was the case for operation counts, the step count is a function of the problem size.

What do you think is the main advantage of using Operation count method?

Representative operation counts provide more guidance and insight for comparisons of two algorithms that are run on different computers, and even permits us to compare algorithms implemented with different computer languages.


2 Answers

If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.

like image 62
Greg Hewgill Avatar answered Sep 24 '22 00:09

Greg Hewgill


Using "the number of operations" is a bad idea when thinking about performance. It doesn't take into account the differences between the best case/worst case cycle counts for each operation, the costs of cache misses, pipeline misses, potential (automatic) parallelisation etc.

As Greg says, usually it's a better idea for a microbenchmark to just run the same code enough times to get a decent span of time.

Even better is to run your whole application with a realistic workload and measure the metrics you're really interested in, but that's a different matter...

What is certainly useful is to work out the complexity of your code - know when a method is going to be O(1), O(log n), O(n) etc. That typically doesn't involve knowing the details of what the individual instructions in C++ do - although you do need to know the complexity of anything you call. (Joel's story of Shlemiel the Painter and strlen being the most obvious example.)

like image 34
Jon Skeet Avatar answered Sep 23 '22 00:09

Jon Skeet