Memory optimization method and device and storage medium

By adding hook functions to the program to collect execution times and reorganize the file structure, the problem of low memory utilization is solved, continuous distribution of high-frequency functions is achieved, page replacement is reduced, and memory usage efficiency and program stability are improved.

CN118733056AInactive Publication Date: 2024-10-01ZHEJIANG DAHUA TECH CO LTD

Patent Information

Application Number
CN202411225621.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-09-03
Publication Date
2024-10-01
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

In the existing technology, when the program is running, high-frequency and low-frequency functions are adjacently distributed in the memory, resulting in low memory utilization, and there is a lack of effective solutions.

Method used

By adding the function collection compilation option, a hook function is generated for the source code, the number of function executions is collected, and a new link script is generated based on the number of executions. The program files are reorganized so that high-frequency functions are continuously distributed in the memory and page replacement overhead is reduced.

Benefits of technology

Improved memory usage efficiency, reduced page replacement frequency, and improved program stability and responsiveness.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118733056A_ABST
    Figure CN118733056A_ABST
Patent Text Reader

Abstract

The invention relates to a memory optimization method and device and a storage medium, and the method comprises the steps: adding a function collection compiling option, compiling a source code, and generating a first target file; the first target file comprises a hook function added for a function in the source code by a compiler in the compiling process, and the hook function is used for collecting information of the function; according to the first link script, linking the first target file to generate a first executable file; executing the first executable file, and obtaining the number of execution times of the function in the source code; the first executable file comprises a hook function; generating a second link script according to the execution times and the first link script; and according to the second link script, compiling and linking the source code to generate a second executable file, so that function discrete distribution states of different execution frequencies of the program file or the executable file are orderly arranged according to the execution times, the overhead of page replacement is reduced, and the memory use efficiency is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present application relates to the field of computer technology, and in particular to a memory optimization method, device and storage medium. Background Art

[0002] The compilation and linking of programs are very important links in software development. For example, the compilation and linking of C language programs is the process of converting source code into executable files. During the compilation process, the source code will be converted into assembly code by the compiler, and then the assembly code will be converted into machine language code by the assembler to generate the target file. During the linking process, the target files will be combined into the final executable file by the linker. In C language programs, different functions are organized together according to the order in which they are defined in the source code. This means that in the executable file, the addresses of these functions will also be allocated according to the order in which they are in the source code. This organization method causes high-frequency and low-frequency executed functions to be close to each other in address when the program is running.

[0003] Due to this phenomenon, when the executable file is loaded into the physical memory, some codes of the functions that are executed less frequently will also be loaded in. This will cause part of the memory space to be occupied by the codes that are used less frequently, reducing the utilization of the memory and resulting in low memory utilization.

[0004] There is no effective solution to the problem of low memory utilization in the prior art. Summary of the invention

[0005] The embodiments of the present application provide a memory optimization method, device and storage medium to solve the problem of low memory utilization in the prior art.

[0006] In a first aspect, an embodiment of the present application provides a memory optimization method, the method comprising: Adding a function collection compilation option, compiling the source code to generate a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information from the function; According to the first link script, link the first target file to generate a first executable file; execute the first executable file to obtain the execution times of the functions in the source code; the first executable file includes the hook function; Generate a second link script according to the execution count and the first link script; The source code is compiled and linked according to the second link script to generate a second executable file.

[0007] In some embodiments, compiling and linking the source code according to the second link script to generate a second executable file includes: Compiling the source code according to preset compilation parameters to generate a second target file; each function in the second target file is an independent segment; The second target file is linked according to the second link script to generate a second executable file.

[0008] In some embodiments, executing the first executable file to obtain the execution count of the function in the source code includes: When the target function is executed, the hook function of the target function is called; When the private data of the current thread is obtained, the private data of the current thread is updated; the private data is used to record the execution information of the function.

[0009] In some embodiments, when the private data of the current thread is acquired, updating the private data of the current thread includes: When the target function is recorded in the private data, the execution count corresponding to the target function in the private data is increased by one.

[0010] In some of the embodiments, after obtaining the private data of the current thread, the method further includes: When the acquisition of private data fails, creating private data of the current thread and initializing the private data of the current thread; Set the initialized private data of the current thread to the current thread object.

[0011] In some embodiments, executing the first executable file to obtain the execution count of the function in the source code includes: The private data of the current thread is stored; the stored private data of the current thread includes the function names of each function after the current thread is executed and the corresponding execution times.

[0012] In some embodiments, generating a second link script according to the execution count and the first link script includes: Inserting groups into the first link script according to the function names of the functions and the corresponding execution times to generate the second link script.

[0013] In some of the embodiments, the hook function includes a function entry hook function and a function return hook function.

[0014] In a second aspect, an embodiment of the present application provides a memory optimization device, the device comprising: A compiling module, used for adding a function collection compiling option, compiling the source code, and generating a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compiling process, and the hook function is used for collecting information from the function; a first linking module, used to link the first target file according to a first linking script to generate a first executable file; an execution module, used to execute the first executable file to obtain the execution times of the functions in the source code; the first executable file includes the hook function; A generating module, configured to generate a second link script according to the execution times and the first link script; The second link module is used to compile and link the source code according to the second link script to generate a second executable file.

[0015] In a third aspect, an embodiment of the present application provides a computer-readable storage medium on which a computer program is stored, and when the computer program is executed by a processor, the steps of the memory optimization method described in the first aspect are implemented.

[0016] Compared with the prior art, a memory optimization method, device and storage medium provided in the embodiments of the present application compile the source code by adding a function collection compilation option to generate a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information about the function; according to the first link script, the first target file is linked to generate a first executable file; the first executable file is executed to obtain the execution count of the function in the source code; according to the execution count and the first link script, a second link script is generated; according to the second link script, the source code is compiled and linked to generate a second executable file, so that the discrete distribution states of functions with different execution frequencies of the program file or executable file are arranged in order according to the execution count, thereby reducing the overhead of page replacement and improving memory usage efficiency.

[0017] Details of one or more embodiments of the present application are set forth in the following drawings and description to make other features, objects, and advantages of the present application more readily apparent. BRIEF DESCRIPTION OF THE DRAWINGS

[0018] The drawings described herein are used to provide a further understanding of the present application and constitute a part of the present application. The illustrative embodiments of the present application and their descriptions are used to explain the present application and do not constitute an improper limitation on the present application. In the drawings: Figure 1It is a schematic diagram of function distribution of a memory page in an embodiment of the present application; Figure 2 is another schematic diagram of function distribution of a memory page according to an embodiment of the present application; Figure 3 It is a hardware structure block diagram of a terminal that executes a memory optimization method according to an embodiment of the present application; Figure 4 is a flow chart of a memory optimization method according to an embodiment of the present application; Figure 5 This is a schematic diagram for comparing the function distribution of a memory page in an embodiment of the present application; Figure 6 is a flowchart of another memory optimization method according to an embodiment of the present application; Figure 7 This is a schematic diagram of a hook function call in an embodiment of the present application; Figure 8 It is a code schematic diagram of collecting function execution information in an embodiment of the present application; Fig. 9 This is a schematic diagram of a code using a red-black tree structure in an embodiment of the present application; Fig.10 It is a logical schematic diagram of a subject for collecting information on the number of times a function is executed in an embodiment of the present application; Fig.11 It is a schematic diagram of a function segmentation in an embodiment of the present application; Fig.12 is another functional segmentation schematic diagram of an embodiment of the present application; Fig.13 It is a schematic diagram of generating a custom link script according to an embodiment of the present application; Fig.14 It is a code schematic diagram of the three-level description of the embodiment of the present application; Fig.15 It is a code schematic diagram of the link script of an embodiment of the present application; Fig.16 It is a structural block diagram of a memory optimization device according to an embodiment of the present application. DETAILED DESCRIPTION

[0019] In order to more clearly understand the purpose, technical solutions and advantages of the present application, the present application is described and illustrated below in conjunction with the accompanying drawings and embodiments.

[0020] Unless otherwise defined, the technical terms or scientific terms involved in this application shall have the general meaning understood by people with general skills in the technical field to which this application belongs. The words "one", "a", "the", "these" and the like in this application do not indicate a quantitative limitation, and they may be singular or plural. The terms "include", "comprise", "have" and any variants thereof involved in this application are intended to cover non-exclusive inclusions; for example, a process, method and system, product or device comprising a series of steps or modules (units) is not limited to the listed steps or modules (units), but may include unlisted steps or modules (units), or may include other steps or modules (units) inherent to these processes, methods, products or devices. The words "connect", "connected", "coupled" and the like involved in this application are not limited to physical or mechanical connections, but may include electrical connections, whether direct or indirect. The "multiple" involved in this application refers to two or more. "And / or" describes the association relationship of associated objects, indicating that there may be three relationships, for example, "A and / or B" may mean: A exists alone, A and B exist at the same time, and B exists alone. Generally, the character " / " indicates that the objects associated with each other are in an "or" relationship. The terms "first", "second", "third", etc. in this application are only used to distinguish similar objects and do not represent a specific ordering of the objects.

[0021] The technical terms involved in the embodiments of the present application are explained below.

[0022] The Linux operating system uses on-demand loading technology to manage the loading of executable files in physical memory. This technology means that when the program is running, part or all of the program content will be loaded into the memory only when needed.

[0023] The process of on-demand loading can be simply divided into the following steps: Program loading: When a user starts an executable file, the operating system will load the program into the memory according to the file format and related information. During this loading process, the entire program is not loaded into the memory, but only a part of it is loaded as needed.

[0024] Page table mapping: Once the program is loaded into memory, the operating system will create a page table to record the correspondence between the program's memory address and storage location. Each entry in the page table points to the physical memory address where the program is located.

[0025] Memory paging: The Linux operating system divides the memory into multiple fixed-size pages, usually 4KB. When a program is executed, the operating system loads the pages that need to be accessed into the memory instead of loading the entire program into the memory.

[0026] Page Fault: When a program needs to access a page that is not loaded into memory, the operating system triggers a Page Fault exception. The operating system then satisfies the program's needs by reading the contents of the page from disk and loading the page into memory.

[0027] Page replacement: If the space in the memory is exhausted, the operating system will select some pages and swap them out to the disk according to a certain page replacement algorithm to provide space for new pages.

[0028] Through the on-demand loading technology, the Linux operating system can effectively manage memory resources and improve the running efficiency of programs. On-demand loading not only saves memory space, but also avoids unnecessary disk read and write operations, and improves the response speed of the program. At the same time, on-demand loading also enables "large" programs to run on "small memory" devices. On-demand loading is an important technology for the Linux operating system to load executable files into memory. It improves memory utilization and program running efficiency by dynamically loading memory pages according to program requirements, providing users with a better user experience.

[0029] When the system faces a memory shortage, the operating system will try to free up memory space through page replacement. Page replacement is to remove some pages that are not frequently used or have not been used for a long time from the memory to provide space for other pages.

[0030] However, frequent page replacement may cause the CPU usage to soar. This is because page replacement involves a large number of disk read and write operations, and the disk access speed is slower than the memory. When the system needs to load the replaced page, the CPU may be in a state of waiting for disk IO operations and cannot perform other tasks.

[0031] Frequent page replacement may cause the CPU to be wasted while waiting for IO operations and cannot be fully utilized. This will cause the system's responsiveness to decrease and cause obvious lag. At the same time, a surge in CPU usage will also increase the system's energy consumption and even cause the program to crash abnormally.

[0032] When developers organize the code, they refer to the module layering, split by module, and aggregate the same functions in one module, which is conducive to the modular understanding of the entire software by developers and more in line with the human thinking model. When the program is running, combined with the computer composition principle and the operating system's management of file data access, there is cross-access of high-frequency execution code and low-frequency execution code in the address linear dimension, which reduces the efficiency of memory use.

[0033] For example, a function that is executed 100,000 times per second and a function that may be executed less than an hour are next to each other in memory. When they are loaded into memory, some of the frequently used and rarely implemented data occupy the memory. As a non-limiting example, Figure 1 and Figure 2 As shown in the figure, within a certain statistical period, the number of execution times of a function in a certain memory page corresponding to the program. Figure 1 and Figure 2 As can be seen from the figure, functions with different execution frequencies are loaded into the memory in pages because their addresses are continuous and because of the way Linux manages memory pages, while functions with high frequency are scattered in different pages. Figure 1 and Figure 2 It can be seen that because functions of different frequencies are mixed together, the operating system needs to use more memory to load program data; when memory is tight, frequent page replacement is also required.

[0034] In summary, a memory optimization method is provided in an embodiment of the present application. By adjusting the organizational structure of the program, i.e., the linking process, the memory utilization efficiency is improved, page replacement is reduced, and the stability of program operation is improved without changing the source program.

[0035] The method embodiments provided in the embodiments of the present application can be executed in a terminal, a computer or a similar computing device. For example, running on a terminal, Figure 3 is a hardware structure block diagram of a terminal that executes a memory optimization method according to an embodiment of the present application. Figure 3 As shown, the terminal may include one or more ( Figure 3 Only one is shown in the figure) a processor 102 and a memory 104 for storing data, wherein the processor 102 may include but is not limited to a processing device such as a microprocessor MCU or a programmable logic device FPGA. The above terminal may also include a transmission device 106 and an input and output device 108 for communication functions. It can be understood by those skilled in the art that Figure 3 The structure shown is for illustration only and does not limit the structure of the above terminal. Figure 3 More or fewer components as shown, or with Figure 3 Different configurations shown.

[0036] The memory 104 can be used to store computer programs, for example, software programs and modules of application software, such as a computer program corresponding to a memory optimization method in an embodiment of the present application. The processor 102 executes various functional applications and data processing by running the computer program stored in the memory 104, that is, to implement the above method. The memory 104 may include a high-speed random access memory, and may also include a non-volatile memory, such as one or more magnetic storage devices, flash memory, or other non-volatile solid-state memory. In some instances, the memory 104 may further include a memory remotely arranged relative to the processor 102, and these remote memories may be connected to the terminal via a network. Examples of the above-mentioned network include, but are not limited to, the Internet, an intranet, a local area network, a mobile communication network, and combinations thereof.

[0037] The transmission device 106 is used to receive or send data via a network. The above network includes a wireless network provided by a communication provider of the terminal. In one example, the transmission device 106 includes a network adapter (Network Interface Controller, referred to as NIC), which can be connected to other network devices through a base station so as to communicate with the Internet. In one example, the transmission device 106 can be a radio frequency (Radio Frequency, referred to as RF) module, which is used to communicate with the Internet wirelessly.

[0038] The present application provides a memory optimization method. Figure 4 is a flow chart of a memory optimization method according to an embodiment of the present application. Figure 4 As shown, the process includes the following steps: Step S410, adding a function collection compilation option, compiling the source code, and generating a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information from the function.

[0039] In this step, a function collection compilation option is added to the compiler, such as adding the compilation option of "-finstrument-functions" of the gcc / clang compiler. Among them, "-finstrument-functions" is an example of a function collection compilation option, which is an option of the compiler for tracking function calls. When this option is added during compilation and linking, the gcc / clang compiler will automatically call a hook function at the entrance and exit of the function, and the hook function is used to collect information about the function, that is, after adding the compilation option of "-finstrument-functions" of the gcc / clang compiler, the source code is compiled, and the generated first target file will automatically call the hook function at the entrance and exit of the function. As a non-limiting example, the gcc / clang compiler will automatically call the function entry hook function at the entrance of the function, such as the __cyg_profile_func_enter function, and call the function return hook function at the exit of the function, such as the __cyg_profile_func_exit function. By customizing these two functions, various monitoring and processing logics for function calls can be implemented, thereby collecting information about the function.

[0040] Step S420: linking the first target file according to the first linking script to generate a first executable file.

[0041] In this step, the hook function is integrated during linking, and the first target file is linked with the first link script to generate a first executable file. The first link script here is the original link script of the source code.

[0042] Step S430, executing the first executable file to obtain the execution times of the functions in the source code; the first executable file includes a hook function.

[0043] In this step, the first executable file is executed according to the usage scenario to obtain the execution times of each function in the source code, and the first executable file includes a hook function.

[0044] Step S440: Generate a second link script according to the execution count and the first link script.

[0045] In this step, a second linker script is generated according to the execution count and the first linker script.

[0046] Step S450: compile and link the source code according to the second link script to generate a second executable file.

[0047] In this step, the source code is compiled and linked according to the second link script to generate a second executable file. That is, the second executable file is compiled and linked according to the number of executions of the function in the source code, that is, the second executable file is stored according to the number of executions of the function, and when the second executable file is loaded into the memory, the functions are arranged in order according to the execution frequency or number, that is, the addresses of high-frequency functions in the memory are close together, thereby reducing the overhead of page replacement and improving memory usage efficiency.

[0048] The memory optimization method in the embodiment of the present application can arrange the discrete distribution states of functions of different execution frequencies of program files or executable files in an orderly manner according to the execution frequency (number of times), thereby reducing the overhead of page replacement and improving memory usage efficiency. The effect of the order of changes of program files or executable files in memory is as follows: Figure 5 As shown. Functions within a page (4KB by default, a function is usually several hundred bytes) are frequently used. During the execution of the CPU, when a high-frequency function is hit, other high-frequency functions will also be loaded in, reducing the page errors caused by the function not being in the memory to frequently load other programs into the memory. For occasionally hitting a low-frequency function, a page error is generated and loaded into the memory. Due to the low frequency of use, the page will be replaced within a period of time (or when the memory is tight).

[0049] In this embodiment, by adding a function collection compilation option, the source code is compiled to generate a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information about the function; according to the first link script, the first target file is linked to generate a first executable file; the first executable file is executed to obtain the execution count of the function in the source code; according to the execution count and the first link script, a second link script is generated; according to the second link script, the source code is compiled and linked to generate a second executable file, so that the discrete distribution states of functions with different execution frequencies of the program file or executable file are arranged in order according to the execution count, thereby reducing the overhead of page replacement and improving memory usage efficiency.

[0050] In some of the embodiments, the source code is compiled and linked according to the second link script to generate a second executable file, including: compiling the source code according to preset compilation parameters to generate a second target file; linking the second target file according to the second link script to generate a second executable file.

[0051] In this embodiment, since the default linking method of the gcc / clang compiler is to link and package into an executable file based on the target file (usually the file with the suffix of .o / .obj / oxx) generated by the source file (the file with the suffix of .c / .cpp / .cxx), the order of the function in the program is consistent with the order in the source file, and it is not based on the function. The preset compilation parameters here are the compilation parameters of the compiler, such as the compilation parameters of the gcc / clang compiler. In order to enable the link to be based on individual functions, it is necessary to combine the compilation parameter "--ffunction-sections" of the gcc / clang compiler, whose function is to instruct the compiler to place each function in an independent code segment (section), that is, each function in the generated second target file is an independent segment.

[0052] In some of the embodiments, a first executable file is executed to obtain the execution count of a function in the source code, including: when a target function is executed, a hook function of the target function is called; when private data of the current thread is obtained, the private data of the current thread is updated; and the private data is used to record the execution information of the function.

[0053] In this embodiment, if it is the first time that the current thread calls a function to enter the hook function, it will fail to obtain private data at this time, so the thread private data is first created and the private data is initialized. The initialization here mainly initializes the structure maintained by the function information. When the private data of the current thread is obtained, the private data of the current thread is updated. The updating of the private data of the current thread here can be when the target function is recorded in the private data, the execution count corresponding to the target function in the private data is increased by one. For example, the Posix C function pthread_getspecific in the Linux environment is used to maintain the private information of the thread. If it is C++ language, the corresponding encapsulation function in the language can be used to maintain the private information of the thread.

[0054] In some of the embodiments, after obtaining the private data of the current thread, the method further includes: when obtaining the private data fails, creating the private data of the current thread and initializing the private data of the current thread; setting the initialized private data of the current thread into the current thread object.

[0055] In some of the embodiments, executing a first executable file and obtaining the execution count of a function in a source code includes: storing private data of a current thread; the stored private data of the current thread includes the function name and the corresponding execution count of each function after the current thread is executed.

[0056] In this embodiment, one is that the storage is performed when the thread ends, and it can also be a staged storage, because some programs may continue to run as long as the power is not cut off, and some threads will not end. If the storage is only performed when the thread ends, then the statistical information of these threads that have not ended cannot be obtained, so some intermittent data storage for the threads can be added, and it can also be stored when the thread ends.

[0057] In some of the embodiments, generating the second link script according to the execution count and the first link script includes: inserting groups into the first link script according to the function names of the functions and the corresponding execution counts to generate the second link script.

[0058] In some of the embodiments, the hook function includes a function entry hook function and a function return hook function.

[0059] The present application provides a memory optimization method. Figure 6 is a flowchart of another memory optimization method according to an embodiment of the present application. Figure 6 As shown, the process includes the following steps: Step S610, add a hook function at the entry and return of each function; the acquisition module implements the hook function, and uses the default link script to link the acquisition module to the target program.

[0060] In this step, the acquisition module implements the hook function, and the source code is compiled and linked with the default link script to generate the target program. The file generated by compiling the source code with the hook function added is the first target file in the aforementioned embodiment. The target program here is the first executable file in the aforementioned embodiment. Adding an acquisition module to implement the hook function of function entry and return only requires linking the acquisition module to the target program during the program linking process. The default link script here is the first link script in the aforementioned embodiment. If the -finstrument-functions compilation option is added when the source code is compiled, the acquisition module is integrated during linking, and the default link script is used to build and generate the target program.

[0061] Step S620: Run the target program according to the usage scenario.

[0062] Step S630, obtaining the execution count (frequency) information of the function in the target program.

[0063] Step S640: Generate a link script arranged according to function execution frequency information.

[0064] In this step, the linker script generator generates a linker script arranged according to the function execution frequency information. The linker script arranged according to the function execution frequency information here is the second linker script in the above embodiment.

[0065] Step S650, compile the source code so that the link unit can use the function as the minimum granularity; use the link script arranged according to the function execution frequency information during linking; and construct and generate a new target program.

[0066] In this step, the -ffunction-sections compilation option is added when the source code is compiled. The file generated by compiling with the -ffunction-sections compilation option is the second target file in the aforementioned embodiment. When linking, the link script arranged by frequency is used to build and generate a new target program. The new target program here is the second executable file in the aforementioned embodiment.

[0067] The memory optimization method provided in this embodiment arranges the discrete distribution states of functions with different execution frequencies in order according to the execution frequency (number of times), thereby reducing the overhead of page replacement and improving memory usage efficiency.

[0068] The embodiments of the present application are described and illustrated below.

[0069] In embedded software development activities, the conventional method is: compile and link the developed code according to the default linking method of the compiler to generate an executable program; test and verify the executable file in the device, and the tester simulates the usage scenario of the device to perform verification testing.

[0070] The main implementation steps of a memory optimization method provided in the embodiment of the present application are: S1. Compile and link the program code in a conventional manner to generate an executable program. At this time, since the execution count information of the function in the code at runtime is unknown, the default method is first used for compilation and linking. Since it is necessary to collect the function execution count information, it is necessary to implant a function execution count information statistics module into the program, that is, the collection module in the aforementioned embodiment. S2. During the product development stage, there will be a test verification environment, one of which is to simulate the user usage scenario to verify whether the function of the device is normal. S3. During the test run, all executed functions will be counted for the number of executions, and the function address and number information will be recorded and reported according to a certain strategy. S4. According to the received function execution information, a link script is generated according to the strategy. S5. The source code is recompiled and linked into a new program. The arrangement of each function of the program is arranged according to the preset execution count, so as to meet the purpose of reducing page replacement when the program is running and improve the efficiency of memory use.

[0071] In order to collect function execution count information, it is necessary to integrate the function execution count statistics module in step S1. Based on the "-finstrument-functions" option feature of the gcc / clang compiler, the __cyg_profile_func_enter and __cyg_profile_func_exit function calls will be added to each compiled function when entering and exiting the function, such as Figure 7 As shown. That is, when compiling the source code, you need to add the "-finstrument-functions" compilation parameter. The function execution count information statistics module needs to implement these two functions specifically. Since each function will add a pair of __cyg_profile_func_enter function and __cyg_profile_func_exit function after being compiled by gcc / clang, you only need to count the number of times the function is executed, so it can be implemented in any of these two functions, such as Figure 8 In the sample code, select to collect function execution information when entering the function. The parameters of the __cyg_profile_func_enter and __cyg_profile_func_exit functions are the starting address of the current function (this_fn) and the return address (that is, the address call_site in the caller function). Among them, this_fn is the current function.

[0072] The specific implementation scheme for collecting the number of execution function information is that each function will enter the __cyg_profile_func_enter function when it is executed, and most programs are multi-threaded. Therefore, in order to meet the multi-thread concurrency and avoid the addition of this statistical logic, which will cause the non-existent critical section between threads (that is, the code fragment that needs to be accessed mutually exclusive), thread private data is used for maintenance, such as the Posix C function pthread_getspecific in the Linux environment to maintain the private information of the thread. If it is C++ language, the corresponding encapsulation function in the language can be used to achieve the same purpose. Each thread maintains a private data structure (structure fields include but are not limited to) as shown in the following sample code. Among them, thread_private_info is private information.

[0073] typedef struct thread_private_info { int tid; / / thread ID int depth; / / Call stack depth struct rb_root root; / / Red-black tree, a collection of all functions executed by the current thread } thread_private_info Since the number of functions executed during the execution of each thread is uncertain, ranging from a few to hundreds, thousands or even tens of thousands, a data structure that is easy to retrieve quickly is needed to maintain the functions supported by the current thread, so that the logic of collecting function count information has the smallest timing impact on the logic of the original program. Different data structures can be selected according to the complexity and size of different programs, such as using a red-black tree structure, std::map in C++, etc. Here, the structure of a red-black tree is taken as an example, and the node structure (structure fields include but are not limited to) is as follows Fig. 9 The sample code in .

[0074] The logic of the main body of the function execution count information collection is as follows Fig.10 As shown, the following steps are included: 1) information collection is implemented in __cyg_profile_func_enter or __cyg_profile_func_exit. This embodiment takes __cyg_profile_func_enter as an information collection point; 2) private data of the thread is obtained; 3) if it is the first time that the current thread calls __cyg_profile_func_enter, the private data will fail to be obtained. First, create thread private data and initialize the private data. The initialization here mainly initializes the structure for maintaining function information, such as the red-black tree mentioned above; the specifics may vary depending on different development languages, or other data structures may be used; 4) Set the created and initialized thread private data to the current thread object, such as calling pthread_setspecific under Linux, store the information, and associate it with the current thread; 5) If it is the first call, there is no record of the current function, so a new function record information structure needs to be added; or it is not found in the existing function records, so a new function record information structure needs to be created; 6) Add the newly created function record information structure to the function set of the thread private information; 7) If the thread private information is obtained in step 2), it means that the current thread is not the first to call __cyg_profile_func_enter, so it can be searched in the function set in the thread private information; 8) If found, directly increase the execution count of the function by 1, that is, increase the corresponding count of this_fn by 1.

[0075] Since threads may be dynamically created and destroyed during program execution, it is necessary to save the function information collected by the thread in time when the thread is destroyed. In this embodiment, the basis for judging thread exit is the depth of the thread call stack. When each function in the source code is compiled into an executable program, __cyg_profile_func_enter is added at the entrance of the function and __cyg_profile_func_exit is added when exiting. Therefore, in the __cyg_profile_func_enter function, the stack depth information of the current thread private data is added by 1, and in the __cyg_profile_func_exit function, the stack depth information of the current thread private data is subtracted by 1. Such as the depth field of the thread_private_info code example. __cyg_profile_func_enter and __cyg_profile_func_exit are called respectively when each function is called and exited. In __cyg_profile_func_enter, depth is increased by 1, and in __cyg_profile_func_exit, depth is decreased by 1. Since each function is the enter and exit of the program, when the thread exits, depth is equal to 0 or 1, depending on the initial value of depth. Therefore, when in the __cyg_profile_func_exit function, if depth is found to be 0 or 1, it can be determined that the thread is destroyed. At this time, it is necessary to immediately store the function execution count information of the current thread in the __cyg_profile_func_exit function (if the device's persistent storage space is sufficient, it can be stored on the local storage medium, or the data can be sent to the data receiving end by communication), and then release the memory resources requested by the thread for storing the function execution count information (the thread private information and function support count information mentioned above).

[0076] Since the address of the function (this_fn) is recorded when the program is running, it is necessary to convert the address into a specific function name in subsequent processing. For specific implementation, you can refer to ELF symbol resolution, or directly use the add2line command line tool in the GNU tool chain to convert the address into a function name.

[0077] After the program has been verified and tested, all the required functions and the corresponding execution times are collected. Based on this information, a link script generator can be used to generate a link script in the order of the number of times the functions are executed, and then passed to the compiler, so that the compiler can reorganize all the functions in the program according to the link order and link to generate a new program. Since the default linking method of gcc / clang is to link and package the target files (usually files with .o / .obj / oxx suffixes) generated by source files (files with .c / .cpp / .cxx suffixes) into an executable file, the order of functions in the program is consistent with the order in the source file, and is not in units of functions. In order to enable the link to be based on individual functions, it is necessary to combine the compilation parameter "--ffunction-sections" of gcc / clang (compile with functions as units) to compile each function into an independent segment. After gcc / clang is compiled with the "--ffunction-sections" parameter, the generated target intermediate file (file with the suffix .obj) can be parsed using the objdump tool (the default ELF parsing tool of the Linux operating system) to view the segment information of each function. Fig.11 and Fig.12 As shown, each function has a corresponding .text.xxx section.

[0078] The link script can describe how the program segments are organized, so the link script generator will combine the function execution count information to set the link order for each function from high to low (or from low to high). The link script can be specified during the linking process through the gcc / clang tool chain (such as the -T option of gcc / clang). The link script generator refers to the function execution count information and automatically modifies the default link script. Fig.13 As shown in the figure, the default script used by the linker in the gcc / clang toolchain is dumped, and a custom linker script is generated based on the function execution frequency information. The linker in the GNU ld toolchain supports arranging by section name, so the linker script generator uses this name sorting feature to achieve the purpose of customizing the linking order. Taking the gcc toolchain as an example, the default linker script can be obtained through the command gcc-Wl, --verbose or ld --verbose.

[0079] The execution count information of all functions is collected, and the function name can be converted through the address. The corresponding relationship table can be constructed, as shown in Table 1. The custom script segment is composed according to the segment name and execution count corresponding to the function.

[0080] Table 1 Correspondence table Custom script segment names can be directly assembled according to the execution count hit_count, such as ".text.sort_by_hist_counts.325" in Table 1, or divided into intervals according to the actual size of the program and the distribution of the execution times of the function, as shown in Table 2.

[0081] Table 2 Interval division table The linker script generator dumps the default script and inserts the grouping into the .text section with the function and count information, using Figure 14 to Figure 15 The three-level description is shown. Fig.15 The first section of code (above the arrow) is the original custom script. Fig.15 The second section of code (below the arrow) is the link script generated in the order of the number of times the function is executed.

[0082] The generated new link script (named sort_by_hit_counts.ld in the example) is finally specified when linking the generated new program. Taking the gcc / clang tool chain as an example, use the -T option: gcc -T sort_by_hit_counts.ld-o<exe.out> , that is, generate a new target program or a new executable file exe.out according to the new link script sort_by_hit_counts.ld.

[0083] The embodiment of the present application proposes a method based on a custom link script to arrange the program according to the execution frequency of the runtime function, and construct a complete construction solution that is beneficial to the program runtime, reducing the page replacement overhead and improving the memory utilization efficiency. The main features of this solution include: 1) adding entry and return hook functions to each function without modifying the source code by the developer. The main feature of the selected solution is to select the compiler's compilation options to implement the addition of hook functions, such as: the "-finstrument-functions" option of the GCC / Clang compiler; 2) adding a collection module to implement the entry and return hook functions of the function, and only need to link the collection module to the program during the program linking process; this method reduces the impact on the entire software development team to a minimum, or even imperceptible; in the normal software testing and verification phase, the execution count information of the program function is imperceptibly collected. This process is completely consistent with the normal software development process (development->testing->problem fixing->retesting), and there is no need to add additional development processes; 3) In the embodiment of the present application, a method is proposed to effectively improve the effective utilization rate of memory. By collecting the number of executions of the function at runtime (or the number of times / frequency within a unit statistical period), combined with the characteristics of the memory management of the Linux operating system, it is proposed to compile and link the program, and arrange it according to the number of function runs / frequency. Compared with the traditional default linking method, the linking method of the embodiment of the present application improves the efficiency of memory use and reduces the problem of page memory fragmentation; 4) In order to implement the entire solution, the embodiment of the present application proposes a custom script generator auxiliary tool to quickly generate custom scripts based on the collected function running frequency information and quickly build new programs; the custom script generator can be divided into groups according to the exact number of executions. In order to collect information on the number of function executions when the program is running, the embodiment of the present application selects the feature "-finstrument-functions" of the gcc / clang tool chain to achieve developer insensitivity, so that the members of the software development team minimize the cost of implementing this embodiment of the application. Compared with gprof (GNU profile tool) which requires the Linux kernel to enable certain feature support, the cost of the embodiment of the present application will be smaller. In order to run the program in multiple threads during the collection process, the embodiment of the present application does not add additional thread mutual exclusion and preemption adjacent areas, and uses thread private data to maintain the collected information. The embodiment of the present application uses call depth information to determine whether the thread is destroyed. When the depth is 0, it indicates that the thread is about to be destroyed. At this time, the information collected by the current thread is promptly transferred and stored (it can be stored in local Flash; it can also be sent out through the network and received and stored at the network server).In order to make the default of using files as the minimum link order unit, the embodiment of the present application selects the feature "-ffunction-sections" of the gcc / clang tool chain to support functions as the minimum link unit (granularity), and combines custom scripts for flexible arrangement. In order to arrange functions as the granularity as expected (according to the number of times / frequency of execution at runtime), the embodiment of the present application formulates the format of a custom link script, and achieves functions of different frequencies through three-level description, so that they can be connected together, and finally achieve the effect of arrangement by number / frequency.

[0084] It should be noted that the steps shown in the above process or the flowchart in the accompanying drawings can be executed in a computer system such as a set of computer executable instructions, and although a logical order is shown in the flowchart, in some cases, the steps shown or described can be executed in an order different from that shown here.

[0085] A memory optimization device is also provided in the embodiments of the present application, and the device is used to implement the above embodiments and preferred implementation modes, which have been described and will not be repeated here. The terms "module", "unit", "subunit", etc. used below can implement a combination of software and / or hardware for a predetermined function. Although the devices described in the following embodiments are preferably implemented in software, the implementation of hardware, or a combination of software and hardware, is also possible and conceivable.

[0086] Fig.16 is a structural block diagram of a memory optimization device according to an embodiment of the present application, such as Fig.16 As shown, the device comprises: A compiling module 10, used to add a function collection compiling option, compile the source code, and generate a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compiling process, and the hook function is used to collect information from the function; A first linking module 20, used to link the first target file according to a first linking script to generate a first executable file; an execution module, used to execute the first executable file to obtain the execution times of the functions in the source code; the first executable file includes the hook function; A generating module 30, configured to generate a second link script according to the execution times and the first link script; The second linking module 40 is used to compile and link the source code according to the second linking script to generate a second executable file.

[0087] It should be noted that the above modules can be functional modules or program modules, and can be implemented by software or hardware. For modules implemented by hardware, the above modules can be located in the same processor; or the above modules can be located in different processors in any combination.

[0088] An embodiment of the present application also provides an electronic device, including a memory and a processor, wherein a computer program is stored in the memory, and the processor is configured to run the computer program to execute the steps in any one of the above method embodiments.

[0089] Optionally, the electronic device may further include a transmission device and an input / output device, wherein the transmission device is connected to the processor, and the input / output device is connected to the processor.

[0090] Optionally, in the embodiment of the present application, the processor may be configured to perform the following steps through a computer program: S1, adding a function collection compilation option, compiling the source code, and generating a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information from the function; S2, linking the first target file according to the first link script to generate a first executable file; executing the first executable file to obtain the execution times of the function in the source code; the first executable file includes the hook function; S3, generating a second link script according to the execution times and the first link script; S4, compile and link the source code according to the second link script to generate a second executable file.

[0091] It should be noted that the specific examples in the embodiments of the present application can refer to the examples described in the above embodiments and optional implementation modes, and will not be repeated in the embodiments of the present application.

[0092] In addition, in combination with a memory optimization method provided in the above embodiment, a storage medium can also be provided in the embodiment of the present application to implement the method. The storage medium stores a computer program; when the computer program is executed by a processor, any memory optimization method in the above embodiment is implemented.

[0093] It should be understood that the specific embodiments described herein are only used to explain the application, rather than to limit it. Based on the embodiments provided in this application, all other embodiments obtained by ordinary technicians in this field without creative work are within the protection scope of this application.

[0094] Obviously, the drawings are only some examples or embodiments of the present application. For ordinary technicians in the field, the present application can also be applied to other similar situations based on these drawings without creative work. In addition, it is understandable that although the work done in this development process may be complicated and lengthy, for ordinary technicians in the field, certain changes in design, manufacturing or production based on the technical content disclosed in this application are only conventional technical means and should not be regarded as insufficient content disclosed in this application.

[0095] The term "embodiment" in this application refers to a specific feature, structure or characteristic described in conjunction with the embodiment that can be included in at least one embodiment of the present application. The appearance of this phrase in various locations in the specification does not necessarily mean the same embodiment, nor does it mean that it is mutually exclusive with other embodiments and is independent or optional. It is clearly or implicitly understood by those of ordinary skill in the art that the embodiments described in this application can be combined with other embodiments without conflict.

[0096] The above-mentioned embodiments only express several implementation methods of the present application, and the descriptions thereof are relatively specific and detailed, but they cannot be understood as limiting the scope of patent protection. It should be pointed out that, for a person of ordinary skill in the art, several variations and improvements can be made without departing from the concept of the present application, and these all belong to the scope of protection of the present application. Therefore, the scope of protection of the present application shall be subject to the attached claims.

Claims

1. A memory optimization method, It is characterized in that The method comprises: Adding a function collection compilation option, compiling the source code to generate a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compilation process, and the hook function is used to collect information from the function; According to the first link script, link the first target file to generate a first executable file; execute the first executable file to obtain the execution times of the functions in the source code; the first executable file includes the hook function; Generate a second link script according to the execution count and the first link script; The source code is compiled and linked according to the second link script to generate a second executable file.

2. The memory optimization method according to claim 1, It is characterized in that Compiling and linking the source code according to the second link script to generate a second executable file includes: Compiling the source code according to preset compilation parameters to generate a second target file; each function in the second target file is an independent segment; The second target file is linked according to the second link script to generate a second executable file.

3. The memory optimization method according to claim 1, It is characterized in that The executing the first executable file to obtain the execution times of the function in the source code includes: When the target function is executed, the hook function of the target function is called; When the private data of the current thread is obtained, the private data of the current thread is updated; the private data is used to record the execution information of the function.

4. The memory optimization method according to claim 3, It is characterized in that When the private data of the current thread is obtained, the private data of the current thread is updated, including: When the target function is recorded in the private data, the execution count corresponding to the target function in the private data is increased by one.

5. The memory optimization method according to claim 3, It is characterized in that After obtaining the private data of the current thread, the method further includes: When the acquisition of private data fails, creating private data of the current thread and initializing the private data of the current thread; Set the initialized private data of the current thread to the current thread object.

6. The memory optimization method according to claim 3, It is characterized in that The executing the first executable file to obtain the execution times of the function in the source code includes: The private data of the current thread is stored; the stored private data of the current thread includes the function names of each function after the current thread is executed and the corresponding execution times.

7. The memory optimization method according to claim 6, It is characterized in that The step of generating a second link script according to the number of executions and the first link script comprises: Inserting groups into the first link script according to the function names of the functions and the corresponding execution times to generate the second link script.

8. The memory optimization method according to claim 2, It is characterized in that The hook function includes a function entry hook function and a function return hook function.

9. A memory optimization device, It is characterized in that The device comprises: A compiling module, used for adding a function collection compiling option, compiling the source code, and generating a first target file; the first target file includes a hook function added by the compiler to the function in the source code during the compiling process, and the hook function is used for collecting information from the function; a first linking module, used to link the first target file according to a first linking script to generate a first executable file; an execution module, used to execute the first executable file to obtain the execution times of the functions in the source code; the first executable file includes the hook function; A generating module, configured to generate a second link script according to the execution times and the first link script; The second link module is used to compile and link the source code according to the second link script to generate a second executable file.

10. A computer-readable storage medium having a computer program stored thereon, It is characterized in that When the computer program is executed by a processor, the steps of the memory optimization method described in any one of claims 1 to 8 are implemented.

Citation Information

Patent Citations

  • Method, device and system for converging hotspot functions and variables in computer programs

    CN103713933A

  • Performance debugging method on embedded equipment

    CN111813677A

  • Method for prefetching function segment and network equipment

    CN116954717A

  • Instruction cache

    US20100088688A1

Cited By

  • Memory management method, electronic equipment and related device

    CN121542017A