C and C++ comparison on low end MCU.

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi team,

Out of curiosity, I did some comparison on using C and C++ on a low end MCU. The MCU I use is MSP430G2333 (4K Flash, 256B ram). Compiler version: TI v18.1.6.LTS, all default settings, IDE code composer v8.3.1

I found that the code generated with C++ is a little less than the C.
  • C, 80B RAM, 84B Flash
  • C++, 80B RAM, 88B Flash

Is this a fair comparison?

Here is the codes I used for testing:
Code:
#include <msp430.h>

class Test{
public:
    void hello(){
        unsigned long int i = 0xFFFF;
        unsigned long int result = 0;
        P1DIR |= BIT0;
        while(i--){
            WDTCTL = WDTPW | WDTHOLD;   // test register access
            result = result + i;                               // simple calculation
            P1OUT ^= BIT0;                                // toggle a LED
        }
    }

    Test(){
        // nothing
    }

    ~Test(){
        // nothing
    }
private:
    // nothing
};

void hello(){
    unsigned long int i = 0xFFFF;
    unsigned long int result = 0;
    P1DIR |= BIT0;
    while(i--){
        WDTCTL = WDTPW | WDTHOLD;  // test register access
        result = result + i;                              // simple calculation
        P1OUT ^= BIT0;                               // toggle a LED
    }
}

/**
* main.c
*/
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;    // stop watchdog timer

    while(1){
           /* comment out hello() or Test.hello() to test different language */
        hello();
        //Test test;
        //test.hello();
    }
}
 

WBahn

Joined Mar 31, 2012
32,823
It's a fair comparison, but not a definitive one by any means. There are lots of metrics by which to compare the two -- code size is certainly one of them and on resource-starved MCUs is often a critical one. But there is also performance (execution speed) comparisons to consider, which also can be critical on MCUs running at slow clock rates. There are lots and lots of variables involved -- which compiler, which compiler options, which processor just to name perhaps the three most important. Then there is the code itself. If you have a very simple program, then the comparison potentially loses a lot of its value. You need to use a program that is sufficiently complex and that uses the features that one language has that the other doesn't in significant ways. Then you need to do that many times for many types of code in order to build up a truly meaningful comparison. You will likely find that there are some times of programs for which one language results in a better solution and other types for which the other does.

The compilers for a lot of MCUs are not nearly as sophisticated at code optimization as main-line compilers for widely-used MPUs, so how you write your code can also be a major factor. You need to learn what constructs your compiler is good at producing tight code for and which ones it doesn't handle well.
 
Top