- user379612
- 27 minutes ago
- Education
- Replies: 0
user379612 Asks: Calculating inflation for retail data
I am currently using a sales weighted average, on retail price increases, in order to calulate a categories Year-over-Year inflation rate.
I am running into an issue however, when I am using products that previously were subsidized, so their prices were, lets say, $0.10.
This year, they no longer have the subsidy, so they are 10$.
I do not wish to add the subsidy back in, as i would like to know the true inflation numbers.
Now, lets say i have 2 products in this category:
Code:
Baby Food: $0.10 -> $10 Sales=$100, therefore, Inflation = 1000%, weighted_inflation = 1000%*$100 = 1000
Baby Diapers: 10$ -> $12 Sales=$100, therefore, Inflation = 20%, weighted_inflation = 20%*$100 = 20
Now, if I sum our weighted_inflation numbers, and divide by total category sales, i will get the categories aggregate inflation.
i.e. (1000 + 20) / $200 = 5.1 So, our inflation for this category is 510%!
My question is, what is a better way of getting this aggregate inflation of a category, that doesn’t get skewed by extreme price changes, that will still fall in line with how National Retail inflation is calculated/defined.
p.s. Yes National inflation is based on CPI, specifically basket sizes of customers, however they use the same calculations «weighted sales data» to determine this.
SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.
Есть три файла: u1.c, u2.c и common.c
Содержание ut1.c
#include<stdio.h>
void fun1();
int main(){
fun1();
}
Содержание ut2.c
#include<stdio.h>
void fun2();
int main(){
fun2();
}
Содержание common.c
void fun1(){
printf("fun1n");
}
void fun2(){
printf("fun2n");
}
Этапы компиляции: —
gcc -Wall -fprofile-arcs -ftest-coverage ut1.c common.c -o ut1
gcc -Wall -fprofile-arcs -ftest-coverage ut2.c common.c -o ut2
Этапы выполнения: —
./ut1
./ut2
Теперь при запуске gcov common.c идет только покрытие fun2.
-: 0:Source:common.c
-: 0:Graph:common.gcno
-: 0:Data:common.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:void fun1(){
-: 2: printf("fun1n");
-: 3:}
-: 4:
1: 5:void fun2(){
1: 6: printf("fun2n");
1: 7:}
2 ответа
Лучший ответ
Это потому, что вы компилируете common.c два разных раза.
При запуске ваших программ ut1 и ut2 мы можем увидеть следующее предупреждение (проверено с GCC 10):
$ ./ut1
fun1
$ ./ut2
fun2
libgcov profiling error:/tmp/gcov-test/common.gcda:overwriting an existing profile data with a different timestamp
Каждый раз, когда вы компилируете с включенным покрытием, GCC будет назначать контрольную сумму данным покрытия. Эта контрольная сумма в основном используется инструментом gcov для обеспечения совпадения файла gcno и файлов gcda. При компиляции ut1 и ut2 будут использоваться разные контрольные суммы. Поэтому вместо добавления данных покрытия ut2 видит недопустимую контрольную сумму и перезаписывает данные.
Решение состоит в том, чтобы рассматривать common.c как отдельную единицу компиляции и связывать его с ut1 и ut2. Например:
# compile common.c
gcc -Wall --coverage -c common.c -o common.o
# compile ut1 and ut2, and link with common.o
gcc -Wall --coverage ut1.c common.o -o ut1
gcc -Wall --coverage ut2.c common.o -o ut2
Тогда вывод gcov должен быть таким, как ожидалось:
-: 0:Source:common.c
-: 0:Graph:common.gcno
-: 0:Data:common.gcda
-: 0:Runs:2
-: 1:#include<stdio.h>
1: 2:void fun1(){
1: 3: printf("fun1n");
1: 4:}
-: 5:
1: 6:void fun2(){
1: 7: printf("fun2n");
1: 8:}
Если вы не можете изменить способ компиляции вашего проекта, вы можете собрать данные о покрытии с помощью таких инструментов, как lcov или gcovr, а затем объединить их. Например, рабочий процесс с gcovr будет следующим:
-
Скомпилируйте ut1, выполните его и сохраните данные покрытия как отчет gcovr JSON:
gcc -Wall --coverage ut1.c common.c -o ut1 ./ut1 gcovr --json ut1.json rm *.gcda *.gcno -
Скомпилируйте ut2, выполните его и сохраните данные покрытия как отчет gcovr JSON:
gcc -Wall --coverage ut2.c common.c -o ut2 ./ut2 gcovr --json ut2.json -
Создайте комбинированный отчет:
gcovr -a ut1.json -a ut2.json --html-details coverage.html
Хотя gcovr не может выводить текстовые отчеты в стиле gcov, он может отображать покрытие в виде HTML:
Полный код этого ответа находится на странице https://gist.github.com/latk/102b125dff160484f93d8997204fc.
3
amon
27 Июн 2021 в 12:28
Вы можете запускать контрольные прогоны в отдельных каталогах. Тогда беги
lcov --capture --rc lcov_branch_coverage=1 --directory dir_1 --config-file ./lcovrc --output coverage_1.info
lcov --capture --rc lcov_branch_coverage=1 --directory dir_2 --config-file ./lcovrc --output coverage_2.info
Затем объедините файл (покрытие линии или покрытие ветки): coverage_1.info и coverage_2.info
При необходимости сгенерируйте окончательный отчет в формате htmp
genhtml --branch-coverage --output ./generated-coverage/ merged_coverage.info
1
Ilya Zlatkin
4 Авг 2021 в 05:12
Comments
avtikhon
added a commit
to tarantool/tarantool
that referenced
this issue
Apr 13, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358
avtikhon
added a commit
to tarantool/tarantool
that referenced
this issue
Apr 13, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358
Totktonada
pushed a commit
to tarantool/tarantool
that referenced
this issue
Apr 14, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358
Totktonada
pushed a commit
to tarantool/tarantool
that referenced
this issue
Apr 14, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358 (cherry picked from commit 57ab8c2)
Totktonada
pushed a commit
to tarantool/tarantool
that referenced
this issue
Apr 14, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358 (cherry picked from commit 57ab8c2)
Totktonada
pushed a commit
to tarantool/tarantool
that referenced
this issue
Apr 14, 2021
Found that 'actions/checkout' does not remove all temporary files from previous runs in submodules [1], it runs only 'git clean --xffd' [2]: libgcov profiling error:/home/ubuntu/actions-runner/_work/tarantool/tarantool/src/lib/small/CMakeFiles/small.dir/small/small_class.c.gcda:overwriting an existing profile data with a different timestamp To avoid of it added: git submodules foreach --recursive 'git clean -xffd' to 'actions/environment' which is run after each 'actions/checkout'. Part of #5986 [1]: https://github.com/tarantool/tarantool/runs/2318244478?check_suite_focus=true#step:5:4012 [2]: actions/checkout#358 (cherry picked from commit 57ab8c2)
При сборке программы с включенными опциями для GCOV можно получить ошибку на этапе линковки следующего вида:
/usr/bin/ld: ./a.out: hidden symbol `__gcov_merge_add’ in /usr/lib/gcc/i486-linux-gnu/4.1.3/libgcov.a(_gcov_merge_add.o) is referenced by DSO
/usr/bin/ld: final link failed: Nonrepresentable section on output
Скорее всего причина заключается в том, что к исполняемому модулю линкуются библиотеки, которые тоже были скомпилированы с опциями -fprofile-arcs -ftest-coverage.
Простой пример, иллюстрирующий проблему.
Даны два файла:
=== a.cpp
#include <stdio.h>
extern unsigned long myfunc ();
int main (int argc, char **argv)
{
unsigned long z = myfunc();
printf("%08xn", z);
return 0;
}
=== b.cpp
#include <time.h>
unsigned long myfunc ()
{
return time(0);
}
Из файла b.cpp делаем статическую библиотеку libmy.a, а из файла a.cpp — исполняемый модуль a.out:
g++ -c -fprofile-arcs -ftest-coverage b.cpp
g++ -shared -o libmy.a ./b.o
g++ -c -fprofile-arcs -ftest-coverage a.cpp
g++ -o a.out a.o -L. -lmy
Получаем ошибку вида «undefined reference to `__gcov_init’» — забыли подключить библиотеку libgcov.a.
Подключаем к сборке требуемую библиотеку как обычно:
g++ -c -fprofile-arcs -ftest-coverage b.cpp
g++ -shared -o libmy.a ./b.o
g++ -c -fprofile-arcs -ftest-coverage a.cpp
g++ -o a.out a.o -L. -lmy -lgcov
Вот здесь-то и получаем странную ошибку:
/usr/bin/ld: ./a.out: hidden symbol `__gcov_merge_add' in /usr/lib/gcc/i486-linux-gnu/4.1.3/libgcov.a(_gcov_merge_add.o) is referenced by DSO
/usr/bin/ld: final link failed: Nonrepresentable section on output
Исправить это просто. Нужно подключить библиотеку libgcov.a не только к сборке исполняемого модуля, но и к сборке статической библиотеки:
g++ -c -fprofile-arcs -ftest-coverage b.cpp
g++ -shared -o libmy.a ./b.o -lgcov
g++ -c -fprofile-arcs -ftest-coverage a.cpp
g++ -o a.out a.o -L. -lmy -lgcov
Вот и всё. Так нужно поступить с каждой библиотекой, исходный код которой скомпилирован с опциями -fprofile-arcs -ftest-coverage.
Сейчас я работаю над исследованием покрытия кода C и столкнулся со следующей проблемой, версия GCC 4.4.6:
- Добавлен флаг компилятора
CFLAGS = --coverageи вариант компоновщикаLDFLAGS := --coverageorLOCAL_LDLIBS := --coverageи получил ошибку:
undefined reference to '__gcov_init'" and "undefined reference to '__gcov_merge_add'
- Добавлена опция
LOCAL_LDFLAGS := --coverage, и получил ошибку ссылки:
libgcov.a(_gcov.o): in function __gcov_set_sampling_rate: undefined reference to '__gcov_sampling_rate'
libgcov.a(_gcov.o): in function gcov_exit: undefined reference to '__gcov_pmu_profile_filename'
libgcov.a(_gcov.o): in function __gcov_init: undefined reference to '__gcov_pmu_profile_options' '__gcov_pmu_top_n_address'
Может ли кто-нибудь помочь дать некоторые предложения по этому вопросу?
7 ответы
Попробуйте такой подход:
Скомпилируйте код, для которого вы хотите сгенерировать покрытие, со следующими параметрами:
CFLAGS: -fprofile-arcs -ftest-coverage
LFLAGS: -lgcov --coverage
Если это не решит проблему, предоставьте некоторую информацию о структуре вашего приложения, т. е. является ли это отдельной программой или приложением, включающим разделяемые/статические библиотеки и т. д.
Надежда, что помогает!
Создан 24 ноя.
Вы связываетесь с -lgcov?
Если вы используете Makefile, было бы очень полезно взглянуть на него, чтобы помочь вам.
ответ дан 30 мая ’21, 06:05
вы должны предоставить LDFLAGS для решения этой проблемы.
LDFLAGS += " -lgcov --coverage"
Создан 25 фев.
Я не могу быть уверен, какое изменение наконец помогло мне, но я думаю, что это было -fprofile-generate флаг. С помощью GNAT GPS я отправился на Switches вкладку слева, а затем выберите Ada Linker вкладка вверху. Затем я включил флажок для Code Coverage. О да, я нашел это на Builder в той же области, если вы включите Recompile if switches changed флажок, это может спасти много зубного скрежета. Возможно, это замедляет работу профессионалов, но я нашел это полезным.
ответ дан 06 мар ’15, в 18:03
Я обнаружил, что мне нужно поместить «-lgcov» справа от профилируемого объекта, а не во флагах. Что-то типа. gcc -pg -o myprog myprog.o -lgmp.a -lgcov
Создан 21 фев.
У меня была неопределенная ссылка на функции gcov (undefined reference to '__gcov_exit'), в то время как я пытался включить покрытие в проекте C, используя тестовую обвязку C++ (CppUTest). Система сборки была обработана CMake.
Компиляторы и gcov были выровнены по одной версии (gcc --version, g++ --version и gcov --version дал ту же версию), но кажется, что моя система сборки ранее была настроена на использование gcc 5, в то время как использовались g++ 8 и gcov 8 (в результате компоновщик добавил дополнительный каталог: usr/lib/gcc/x86_64-linux-gnu/ 5). Я очистил дерево сборки и сгенерировал его снова благодаря CMake, который исправил ошибку.
ответ дан 10 дек ’21, 12:12
Я тоже видел эту проблему, и, как указывалось в большинстве ответов выше, нам нужно было добавить библиотеки lcov/gcov во время компоновки. Мы используем cmake и в файле CmakeLists.txt мы отсутствовали
target_link_libraries(${TARGET_NAME} PRIVATE gcov)
Это было необходимо, конечно, в дополнение к флагу сборки «—coverage» (обратите внимание, что мы можем использовать «—coverage» или «-fprofile-arcs -ftest-coverage» отдельно)
ответ дан 20 дек ’21, 14:12
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
linker
undefined-reference
gcov
or задайте свой вопрос.
If you are developing Linux or desktop applications with GNU tools, you very likely are familiar with gcov: the GNU coverage tool. It collects data what parts of the code gets executed and represents that in different formats, great to check what is really used in the application code or what has been covered during multiple test runs.
Coverage Information with gcov
line never executed
GNU coverage is possible for resource constraint embedded systems too: it still needs some extra RAM and code space, but very well spent for gathering metrics and improves the firmware quality. As I wrote in “MCUXpresso IDE V11.3.0 for 2021” things are now easier to use, so here is a short tutorial how to use it.
Outline
For how gcov works, have a read at gcov for Embedded. This tutorial shows how to use gcov with the MCUXpresso IDE V11.3.0. As board I’m using the FRDM-K64F, and you can find the example project on GitHub.
NXP FRDM-K64F Board
To generate coverage we need:
- Eclipse with the gcov plugins (they are already installed in MCUXpresso IDE 11.3.0)
- GNU binaries without the ‘arm-none-eabi’ prefix: I use a batch file for this
- A project to collect coverage information
We will instrument source files go produce .gcno files on the host. The instrumented application will generate .gcda files we store on the host using semihosting. The gcov tool then will show the reports in the IDE or on the command line:
General gcov Flow
The files and project used in this article can be found on GitHub.
Creating Project
I recommend to get familiar with gcov using a small and bare metal project. I have created a project with the IDE and the MCUXpresso SDK.
Make sure the project is using newlib (nano) with semihosting:
newlib nano with semihost
This creates the project:
bare metal project
Linker Constructor Symbols
Each instrumented file will generate a special constructor which needs to be called later. To be able to call them, we need to include them into our binary and mark them with special symbols. This is done in MCUXpresso IDE with a special FreeMarker Linker script:
/************************************************ * start of main_text.ldt: * ************************************************/ . = ALIGN(4); *(.text*) /* added in template for gcov: */ . = ALIGN(4); PROVIDE_HIDDEN (__init_array_start = .); KEEP (*(SORT(.init_array.*))) KEEP (*(.init_array*)) PROVIDE_HIDDEN (__init_array_end = .); /************************************************ * end of main_text.ldt * ************************************************/
Create a file named main_text.ldt and place it into the folder linkscripts in the project root (or copy it from GitHub):
linker script entry for gcov
Support Files
To write the data, a few hooks and helpers are needed. You can find them in the ‘gcov’ folder of my project on GitHub:
gcov support files
Add it to the project; we will use it in the next step.
Init and Data Writing
The gcov library needs to be initialized. Include the header file:l
#include "../gcov/gcov_support.h"
Call
gcov_init(); /* initialize library */
at the start of main(). Then run the instrumented code. At the end, call
gcov_write();
to write the data;
gcov init and writing data
Heap and Stack
The application on the board writes the collected data to the host via semi-hosting file I/O. Unfortunately file I/O is not very lightweight, and most issues with using gcov for embedded systems are because lack of stack and heap space.
Typically the default heap and stack size will not be enough, so I recommend to assign a good chunk of memory in case of issues: the more the better.
Heap and Stack Space
Instrumenting Source Files
Each file which shall be instrumented for coverage needs to have the following options added:
-fprofile-arcs -ftest-coverage
I recommend as a starter just to instrument one file, or very few.
added instrumentation option for coverage
custom options for board.c
Finally, add the option
-fprofile-arcs
to the linker settings to ensure it links with the proper library support.
Linker Flags
💡 instead of
-fprofile-arcsthe option--coveragecan be used.
Now it is a good time to perform a Project > Clean followed by a Project > Build. It shall now generate .gcno files in the output folder:
gcno file
Collecting Coverage
Now you can run the application: it will collect information from the instrumented code and write the .gcda files on the host using semi-hosting file I/O:
gcda coverage data files in Debug folder on host
Viewing Coverage Information
Double-click on any of the .gda files and it will open a graphical view:
Coverage Information with gcov
Tadaaaaa! 🙂
Double-clicking on a line shows the information with colors in the source view:
execution coverage
Gcovr
If you want to use the gcov data outside of Eclipse, have a look at https://github.com/gcovr/gcovr. It has a feature to add and combine different coverage data files too.
Summary
Coverage tells which lines of code have been executed. This is very important to get good test coverage and can increase software quality. Traditionally coverage as GNU gcov has been used on host applications, but it is possible to use it for embedded targets as well. The latest NXP MCUXpresso IDE 11.3.0 makes it even easier as all the needed tools are already installed: that way I can start collecting coverage information from the target and view and analyze it on the host.
Happy covering 🙂
Links
- Adding GNU Coverage Tools to Eclipse
- MCUXpresso IDE V11.3.0 for 2021
- GNU Coverage Tool: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
- Code Coverage for Embedded Target with Eclipse, gcc and gcov: https://mcuoneclipse.com/2014/12/26/code-coverage-for-embedded-target-with-eclipse-gcc-and-gcov/
- Code Coverage with gcov, launchpad tools and Eclipse Kinetis Design Studio V3.0.0: https://mcuoneclipse.com/2015/05/31/code-coverage-with-gcov-launchpad-tools-and-eclipse-kinetis-design-studio-v3-0-0/
- Files of this project on GitHub: https://github.com/ErichStyger/mcuoneclipse/tree/master/Examples/MCUXpresso/FRDM-K64F/FRDM-K64F_gcov_bm
Description of problem: gcda:Version mismatch - expected 11.2 (experimental) (B12R) got 10.2 (experimental) Version-Release number of selected component (if applicable): ghdl.x86_64 0.38~dev-13.20201208git83dfd49.fc35 gcc.x86_64 11.2.1-7.fc35 ghdl -v: GHDL 1.0-dev () [Dunoon edition] Compiled with GNAT Version: 11.1.1 20210623 gcov -v: gcov (GCC) 11.2.1 20211203 How reproducible: always Steps to Reproduce: 1. analyze VHDL source with "... -Wc,-ftest-coverage -Wc,-fprofile-arcs ..." 2. elaborate design with "... -Wl,-lgcov ..." 3. start the simulation Actual results: libgcov profiling error:unit_xy.gcda:Version mismatch - expected 11.2 (experimental) (B12R) got 10.2 (experimental) (B02R) Expected results: What ever result the simulation gives but no error message from libgcov.
Comment 1
Dan Horák
2021-12-17 14:00:26 UTC
this will need ghdl to be updated to gcc 11, same as the system gcc is
Comment 2
Ben Cotton
2022-11-29 17:30:17 UTC
This message is a reminder that Fedora Linux 35 is nearing its end of life. Fedora will stop maintaining and issuing updates for Fedora Linux 35 on 2022-12-13. It is Fedora's policy to close all bug reports from releases that are no longer maintained. At that time this bug will be closed as EOL if it remains open with a 'version' of '35'. Package Maintainer: If you wish for this bug to remain open because you plan to fix it in a currently maintained version, change the 'version' to a later Fedora Linux version. Thank you for reporting this issue and we are sorry that we were not able to fix it before Fedora Linux 35 is end of life. If you would still like to see this bug fixed and are able to reproduce it against a later version of Fedora Linux, you are encouraged to change the 'version' to a later version prior to this bug being closed.
Comment 3
Ben Cotton
2022-12-13 16:07:14 UTC
Fedora Linux 35 entered end-of-life (EOL) status on 2022-12-13. Fedora Linux 35 is no longer maintained, which means that it will not receive any further security or bug fix updates. As a result we are closing this bug. If you can reproduce this bug against a currently maintained version of Fedora Linux please feel free to reopen this bug against that version. Note that the version field may be hidden. Click the "Show advanced fields" button if you do not see the version field. If you are unable to reopen this bug, please file a new report against an active release. Thank you for reporting this bug and we are sorry it could not be fixed.


















