Hi!
I have been looking for a comparison table of the relative cost of
operations in C++ because it can be very useful for all. I have found
this:
printf/scanf 1000
new/delete 800
trig. function 500
floating point 100
and so on...
While that may be of some use, it's only an extremely rough guideline at
very best. Just for example, the time for a print or scanf varies widely
based upon the number of conversions involved, the amount of output
produced, and the speed of the device to which the output is written --
it can easily vary by a factor of thousands.
But it doesn´t tell anything about some C++ features, like virtual
functions.
What is the cost of calling a virtual function comparing with a
ordinary function?
You can't reasonably compare them directly. If you want to compare
costs, you need to compare a virtual function to something like a switch
statement that calls any one of a number of functions, or perhaps to
calling a function via a pointer.
When you make such a comparison, the time (of course) depends on the
compiler, but with the modern compilers I've tested, there's essentially
no overhead. For example, here's some output from Joe Orost's Bench++
benchmark:
Test Name: F000006 Class Name: Style
CPU Time: 1.73 nanoseconds plus or minus 0.0866
Wall/CPU: 1.00 ratio. Iteration Count:
1677721600
Test Description:
Time to test a global using a 10-way switch statement
Test Name: F000007 Class Name: Style
CPU Time: 2.73 nanoseconds plus or minus 0.136
Wall/CPU: 1.00 ratio. Iteration Count:
1677721600
Test Description:
Time to test a global using a 10-way sparse switch statement
Test Name: F000008 Class Name: Style
CPU Time: 1.94 nanoseconds plus or minus 0.0969
Wall/CPU: 1.00 ratio. Iteration Count:
1677721600
Test Description:
Time to test a global using a 10-way virtual function class
As you can see, the time for the virtual function version is quite
competitive -- with dense values, the switch statement is marginally
faster, but with sparse values, the switch statement is noticeably
slower.
Although the values vary somewhat depending on the compiler and options
I use, that trend has remained roughly constant.
Could anyone tell me where can I find tables of operations cost for C+
+?
My advice would be to download (or write) and run some code to test the
operations you care about. Writing good test code is definitely a
challenge for even the most experienced programmer.