Stepan1010 Stepan1010 -4 years ago 65
C++ Question

What are the major reasons for run time differences between simple arithmetic operations - VBA vs. C++?

This C++ program takes from 20 to 25 seconds to run on my relatively slow computer:

#include <iostream>

int main()
int i;
double test = 456;

for (i = 0; i < 900000000; i++) {
test = (test / 0.99999999);
std::cout << "The value of test is " << test <<".\n";
return 0;

This excel vba macro takes from 37 to 40 seconds to run on my relatively slow computer:

Sub Macro1()
Dim i As Long
Dim test As Double
test = 456

For i = 0 To 900000000
test = (test / 0.99999999)
Next i

Cells(1, 1).Value = test
End Sub

Is this difference typical(of C++ vs. non-compiled languages)? What are the major factors contributing to this difference in time? Is the fact that C++ is compiled the most important factor? Thanks.


For C++ I used Code::Blocks with GCC

For VBA I used Excel 2010.

For Code::Blocks it has a built in timer in it's console.

For excel I used a an iPhone stopwatch(didn't feeling like using CHighResTimer

Answer Source

Your benchmark is off, the margin should be way larger.

For instance, on my computer, the C++ code takes 7.46s (compiled without optimisations, timed with the Unix time tool); the VBA code by contrast took 46s. This is a much more realistic margin (but I wouldn’t have been surprised by an even larger one – conventional, non-optimising interpreters are usually at least a factor ten slower).

For one thing, VBA first has to read in the code and either interpret it line by line or transform it into an intermediate representation. Nevertheless, this intermediate code representation is still interpreted, not run directly by the CPU (or did you count the compilation time in C++?).1

In addition, VB(A) does a lot of redundant stuff in this code which is absent in C++: for instance, every single integer addition (which is implicit in your code in the incrementation of the For loop variable) is guarded against overflow. Essentially, this VB code

i = i + 1

is transformed to the following pseudo intermediate code:

if i + 1 overflows then
    raise an overflow error
end if
i = i + 1

… for every integer operation. That consumes quite a lot of runtime. The same goes for array (or here: cell) access operations.

1 I think VBA uses an intermediate representation called P-code rather than line by line code interpretation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download