How to optimize code through map files

Publisher:EternalWhisperLatest update time:2021-12-29 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

  When writing code, especially embedded code, the optimization method that can be thought of is generally to set the optimization level of the compiler. Or consider the scope of use of the variable when defining the variable, and then choose a more suitable data type based on the data range. However, this optimization method is relatively vague and there is no intuitive feeling. In order to make the optimization of the code more intuitive, today we will use the map file to optimize the code.


  Let's first look at a simple example.

insert image description here

  This is a very simple test code, which makes the LED light flash in the main program and adds 0.1 to the x variable each time. Does this code need to be optimized? Don't worry, open the map file generated in the project first and take a look.

insert image description here

  The map file is in the List folder in the debug folder of the project directory. Use Notepad to open this file.

insert image description here

  In the middle of the file, there is a section that shows the space occupied by each target file. Look down one by one to find a few locations that occupy a larger amount of space.

insert image description here

  It can be found that the object file float.o occupies a large space compared to other files. So where does this float.o file come from? Seeing float, we can probably guess that this is a floating point related file. There is only one place in the program that uses floating point operations.

insert image description here

  Can this line of code take up so much space? Then try changing the floating point operation to an integer operation.

insert image description here

  Expand x by 10 times, then add 1 each time. Compile the code and reopen the map file to view it.

insert image description here

  At this time, you will find that the float.o file in front of long.o has disappeared. This shows that the float.o file just now was generated by the floating-point operation in the code. Through the observation of the map file, we can draw a conclusion that floating-point operations occupy a lot of space in the microcontroller, so try to convert floating-point operations into integer operations. Otherwise, if the amount of floating-point operations is relatively large, the space of the microcontroller will soon be filled up.


  Next, print out the value of the variable through the serial port.

insert image description here

  Observe the printed value through the serial port assistant

insert image description here

  The values ​​printed by the serial port are also normal. Next, continue to check the map file.

insert image description here

  In the map file, you can see that there are several more files before and after the long.o file, and they take up a lot of space.


  Why is there a very large float.o file? This is because the printf function supports floating point printing. There are floating point numbers in the function, so a float.o file is generated. xprintffull_nomb.o is also generated when the printf function is called.


  As can be seen, the printf function takes up a lot of space. Try to avoid using the printf function in the program. So what should we do when we want to print data? We can use the default output function of the microcontroller serial port to print characters, but there is a new problem. The serial port output is in character format. Now we want to print integers. How to convert integers into character format? We can use a custom function to convert numbers into strings first, and then output the strings through the serial port.


  First, write a function that converts an integer to a string.


void int2str(int n, char *str)

{

    char buf[10] = "";

    int i = 0;

    int len ​​= 0;

    int temp = n < 0 ? -n: n; // temp is the absolute value of n


    if (str == NULL)

    {

        return;

    }

    while(temp)

    {

        buf[i++] = (temp % 10) + '0'; //Store each bit of temp into buf

        temp = temp / 10;

    }


    len = n < 0 ? ++i: i; //If n is a negative number, one more bit is needed to store the negative sign

    str[i] = 0; //The end is the terminator 0

    while(1)

    {

        i--;

        if (buf[len-i-1] ==0)

        {

            break;

        }

        str[i] = buf[len-i-1]; //Copy the characters in the buf array to the string

    }

    if (i == 0 )

    {

        str[i] = '-'; //If it is a negative number, add a minus sign

    }

}


  Next, write serial port related functions.


//Send a single character

void SendChar( unsigned char dat )

{

    while( ( UART1_SR & 0x80 ) == 0x00 ); //Send data register empty

    UART1_DR = date;

}

//Send string

void SendString( unsigned char* s )

{

    while( 0 != *s )

    {

        SendChar( *s );

        s++;

    }

}


  Modify the main function code below.


void main( void )

{

    int  x = 10;

    char str[100] = {0};

        

    __asm( "sim" ); //Disable interrupts

    SysClkInit();

    delay_init( 16 );

    LED_GPIO_Init();

    Uart1_IO_Init();

    Uart1_Heat( 9600 );

    __asm( "rim" ); // Enable interrupt


    while( 1 )

    {

        LED = ~LED;


        x += 1;    

        int2str(x,str);

        SendString(str);

        SendString("rn");

        delay_ms( 1000 );

    }

}


  First, the variable x is converted to a string using the int2str function, then the string is printed out using the SendString function, and finally SendString is called again to print the carriage return and line feed characters. The printing effect is as follows:

insert image description here

  Next, let's take a look at the space occupied by the map file.

insert image description here

  From the map file, we can see that compared with directly using the printf function, using a custom function to implement the printing function saves a lot of space. By observing the target file size in the map file, we can intuitively see the specific difference between the optimized code and the unoptimized code during the program optimization process. In this way, we will have a clear plan in the process of debugging the code, and will not be like a headless fly bumping around.

Reference address:How to optimize code through map files

Previous article:Using STM8 microcontroller + NTC thermistor to make a simple temperature inspection instrument
Next article:Check the code size in IAR software

Recommended ReadingLatest update time:2024-11-15 17:26

Introduction to Stm8 bootloader
This application note is specifically for STM8 firmware and system designers who need to implement a product with In-application programming (IPA) features, based on the stm8 microprocessor. The stm8 is a family of 8-bit microcontrollers that use a flash memory to store the user program code or firmware. IAP allows th
[Microcontroller]
STM8 Programming Quick Start
  ST TOOLS is the official software designated by ST for developing ST MCUs. Its programming functions are extremely powerful. The following is a quick introduction to using STVP programming program in ST TOOLS.   First, you need to perform initial configuration of the software and hardware and connect the devices c
[Microcontroller]
STM8 Programming Quick Start
Low power consumption processing solution for STM8 microcontroller
To design low power consumption, we need to consider several aspects: 1. Low power consumption of peripherals. All unnecessary peripheral modules are turned off. 2. GPIO processing: it is best to process unnecessary IO as floating input. 3. For the main clock processing, first reduce it to the lowest internal LSI cloc
[Microcontroller]
Low power consumption processing solution for STM8 microcontroller
Can stm8 pins be used as touch input
I have developed consumer electronic products with touch button functions. At first, I didn’t know that the STM8 pins could realize the touch function, so I write it here for everyone. 1 Written in front When we develop products with touch function, the first thing we may consider is to buy a touch chip. But for con
[Microcontroller]
Can stm8 pins be used as touch input
STM8 ROP programming
FLASH- CR1 = FLASH_CR1_RESET_VALUE; FLASH- CR2 = FLASH_CR2_RESET_VALUE; FLASH- NCR2 = FLASH_NCR2_RESET_VALUE; FLASH- IAPSR &= (uint8_t)(~FLASH_IAPSR_DUL); FLASH- IAPSR &= (uint8_t)(~FLASH_IAPSR_PUL); (void) FLASH- IAPSR; /* Reading of this register causes the clearing of status flags */     #ifdef USE_ROP_ENABLE
[Microcontroller]
STM8 interrupt vector table
// Copyright (c) 2009, Wolver Wang, Innov Inc. R&D Center // wolver@21com.com // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above cop
[Microcontroller]
STM8|STM32 watchdog usage
Both STM8 and STM32 are equipped with independent watchdogs, and their role is self-evident. The following are examples of using independent watchdogs for STM8 and STM32:       For STM32 MCU: #define SYS_IWDG_OPEN        IWDG- KR=0xCCCC; #define SYS_IWDG_FEED        IWDG- KR=0xAAAA; void SystemIWDG_Config(uint32 Ove
[Microcontroller]
Introduction, download, installation and registration tutorial of IAR for STM8
1. Introduction 1. About IAR for STM8 IAR for STM8 is an embedded work platform, mainly used in the development of STM8 series chips. Now (version 3.10 in 2018) it can support all STM8 chips on the market. Personally, I think there is not much difference between IAR for STM8 and Keil. As long as you are familiar w
[Microcontroller]
Introduction, download, installation and registration tutorial of IAR for STM8
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号