- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我的 C++11 程序正在执行序列化数据的在线处理,循环需要运行数百万个内存位置。计算效率是必须的,我担心的是,在这样的循环中调用函数或类会产生不必要的操作,从而影响效率,例如在不同的变量范围之间传递操作所需的几个指针值。
为了举例说明,让我们考虑以下虚拟示例,其中“某事”是重复的操作。请注意,“something”中的代码使用循环范围内的变量。
do {
something(&span,&foo);
spam++
foo++
if ( spam == spam_spam ) {
something(&span,&foo);
other_things(&span,&foo);
something(&span,&foo);
}
else {
something(&span,&foo);
still_other_things(&span,&foo);
something(&span,&foo);
}
}
while (foo<bar);
有没有办法重复代码块并避免使用不必要的操作移动和复制变量?在此类循环中使用函数和类实际上是否意味着额外的操作以及如何避免它?
更新
按照建议,我使用下面提供的代码运行了一些测试。我测试了几个关于如何调用简单增量 1 亿次的选项。我在 Hyper-V 下的 x86_64 虚拟机上通过 RHEL 7 Server 7.6 使用 GCC。
最初,使用“g++ -std=c++17 -o test.o test.cpp”编译
简单循环计算(基线):211.046ms
内联函数:468.768 毫秒
Lambda 函数:253.466 毫秒
定义宏:211.995ms
函数传递值:466.986ms
函数传递指针:344.646ms
带 void 的函数:190.557 毫秒
对象方法与成员操作:231.458ms
对象方法传递值:227.615ms
从这些结果中,我意识到编译器没有采用内联建议,即使在尝试按照 g++ doesn't inline functions 中的建议将其膨胀后也是如此。
后来,按照 Mat 在同一篇文章的回答中的建议,我使用“g++ -std=c++17 -O2 -o test.o test.cpp”打开了编译器优化,并得到了以下结果与未优化的测试相比,迭代次数相同。
简单循环计算(基线):62.9254ms
内联函数:65.0564 毫秒
Lambda 函数:32.8637 毫秒
定义宏:63.0299ms
函数传递值:64.2876ms
函数传递指针:63.3416ms
带 void 的函数:32.1073ms
对象方法与成员操作:63.3847ms
对象方法传递值:62.5151ms
到此为止的结论:
内联函数不是好的选择,因为无法确定编译器将如何真正接受它,结果可能与使用标准函数一样糟糕。
“定义宏”和“lambda 函数”是内联的更好替代方法。每个都有其优点和特点,#define 更灵活。
使用对象成员和方法可以很好地平衡解决任何情况下的问题,同时以更易于维护和优化的形式维护代码。
调整编译器是值得的;
遵循用于测试的代码:
// Libraries
#include <iostream>
#include <cmath>
#include <chrono>
// Namespaces
using namespace std;
using namespace std::chrono;
// constants that control program behaviour
const long END_RESULT = 100000000;
const double AVERAGING_LENGTH = 40.0;
const int NUMBER_OF_ALGORITHM = 9;
const long INITIAL_VALUE = 0;
const long INCREMENT = 1;
// Global variables used for test with void function and to general control of the program;
long global_variable;
long global_increment;
// Function that returns the execution time for a simple loop
int64_t simple_loop_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Perform the computation for baseline
do {
local_variable += local_increment;
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return(duration_cast<microseconds>( timer_stop - timer_start ).count());
}
// Functions that computes the execution time when using inline code within the loop
inline long increment_variable() __attribute__((always_inline));
inline long increment_variable(long local_variable, long local_increment) {
return local_variable += local_increment;
}
int64_t inline_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Perform the computation for baseline
do {
local_variable = increment_variable(local_variable,local_increment);
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Functions that computes the execution time when using lambda code within the loop
int64_t labda_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// define lambda function
auto lambda_increment = [&] {
local_variable += local_increment;
};
// Perform the computation for baseline
do {
lambda_increment();
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// define lambda function
#define define_increment() local_variable += local_increment;
// Functions that computes the execution time when using lambda code within the loop
int64_t define_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Perform the computation for baseline
do {
define_increment();
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Functions that compute the execution time when calling a function within the loop passing variable values
long increment_with_values_function(long local_variable, long local_increment) {
return local_variable += local_increment;
}
int64_t function_values_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Perform the computation for baseline
do {
local_variable = increment_with_values_function(local_variable,local_increment);
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Functions that compute the execution time when calling a function within the loop passing variable pointers
long increment_with_pointers_function(long *local_variable, long *local_increment) {
return *local_variable += *local_increment;
}
int64_t function_pointers_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Perform the computation for baseline
do {
local_variable = increment_with_pointers_function(&local_variable,&local_increment);
} while ( local_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Functions that compute the execution time when calling a function within the loop without passing variables
void increment_with_void_function(void) {
global_variable += global_increment;
}
int64_t function_void_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// set global variables
global_variable = local_variable;
global_increment = local_increment;
// Perform the computation for baseline
do {
increment_with_void_function();
} while ( global_variable != END_RESULT);
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Object and Function that compute the duration when using a method of the object where data is stored without passing variables
struct object {
long object_variable = 0;
long object_increment = 1;
object(long local_variable, long local_increment) {
object_variable = local_variable;
object_increment = local_increment;
}
void increment_object(void){
object_variable+=object_increment;
}
void increment_object_with_value(long local_increment){
object_variable+=local_increment;
}
};
int64_t object_members_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Create object
object object_instance = {local_variable,local_increment};
// Perform the computation for baseline
do {
object_instance.increment_object();
} while ( object_instance.object_variable != END_RESULT);
// Get the results out of the object
local_variable = object_instance.object_variable;
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
// Function that compute the duration when using a method of the object where data is stored passing variables
int64_t object_values_computation(long local_variable, long local_increment) {
// Starts the clock to measure the execution time for the baseline
high_resolution_clock::time_point timer_start = high_resolution_clock::now();
// Create object
object object_instance = {local_variable,local_increment};
// Perform the computation for baseline
do {
object_instance.increment_object_with_value(local_increment);
} while ( object_instance.object_variable != END_RESULT);
// Get the results out of the object
local_variable = object_instance.object_variable;
// Stop the clock to measure performance of the silly version
high_resolution_clock::time_point timer_stop = high_resolution_clock::now();
return duration_cast<microseconds>( timer_stop - timer_start ).count();
}
int main() {
// Create array to store execution time results for all tests
pair<string,int64_t> duration_sum[NUMBER_OF_ALGORITHM]={
make_pair("Simple loop computation (baseline): ",0.0),
make_pair("Inline Function: ",0.0),
make_pair("Lambda Function: ",0.0),
make_pair("Define Macro: ",0.0)
make_pair("Function passing values: ",0.0),
make_pair("Function passing pointers: ",0.0),
make_pair("Function with void: ",0.0),
make_pair("Object method operating with members: ",0.0),
make_pair("Object method passing values: ",0.0),
};
// loop to compute average of several execution times
for ( int i = 0; i < AVERAGING_LENGTH; i++) {
// Compute the execution time for a simple loop as the baseline
duration_sum[0].second = duration_sum[0].second + simple_loop_computation(INITIAL_VALUE, INCREMENT);
// Compute the execution time when using inline code within the loop (expected same as baseline)
duration_sum[1].second = duration_sum[1].second + inline_computation(INITIAL_VALUE, INCREMENT);
// Compute the execution time when using lambda code within the loop (expected same as baseline)
duration_sum[2].second = duration_sum[2].second + labda_computation(INITIAL_VALUE, INCREMENT);
// Compute the duration when using a define macro
duration_sum[3].second = duration_sum[3].second + define_computation(INITIAL_VALUE, INCREMENT);
// Compute the execution time when calling a function within the loop passing variables values
duration_sum[4].second = duration_sum[4].second + function_values_computation(INITIAL_VALUE, INCREMENT);
// Compute the execution time when calling a function within the loop passing variables pointers
duration_sum[5].second = duration_sum[5].second + function_pointers_computation(INITIAL_VALUE, INCREMENT);
// Compute the execution time when calling a function within the loop without passing variables
duration_sum[6].second = duration_sum[6].second + function_void_computation(INITIAL_VALUE, INCREMENT);
// Compute the duration when using a method of the object where data is stored without passing variables
duration_sum[7].second = duration_sum[7].second + object_members_computation(INITIAL_VALUE, INCREMENT);
// Compute the duration when using a method of the object where data is stored passing variables
duration_sum[8].second = duration_sum[8].second + object_values_computation(INITIAL_VALUE, INCREMENT);
}
double average_baseline_duration = 0.0;
// Print out results
for ( int i = 0; i < NUMBER_OF_ALGORITHM; i++) {
// compute averave from sum
average_baseline_duration = ((double)duration_sum[i].second/AVERAGING_LENGTH)/1000.0;
// Print the result
cout << duration_sum[i].first << average_baseline_duration << "ms \n";
}
return 0;
}
最佳答案
如果代码足够短,可以声明为内联,编译器会把它放入内联。如果不是,那么重复它可能无济于事。
但是,老实说,这是最不有效的优化形式。关注高效的算法和缓存高效的数据结构。
关于c++ - 如何在不使用函数或类的情况下重复代码段以实现 C++ 中的高性能循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55383866/
我想知道如何考虑需要您做出某些选择才能看到最终结果的搜索系统。我说的是 select 表单,您可以在其中根据您的选择继续操作,然后您会看到结果。 下面描述了我正在谈论的一个随机示例。想象一下 Init
您好,我目前正在编写一些软件来管理我们的库存。我搜索了 2 个表 master_stock(保存每一个股票代码和描述)库存(保存库存代码、地点、数量...) 一切都很好,但这是我遇到的问题。 假设我的
我有 2 个表,我想合并其数据。id 是我的关键字段(增量且不同)。表1和表2字段说明例如:id - 名称 - 值 我想将表2的所有数据插入表1,它们有不同的数据,但在某些行中有相同的id。 所以当我
我正在努力解决汇编中的一个问题,我必须获取十六进制代码的第一个字节 (FF) 并将其复制到整个值中: 0x045893FF input 0xFFFFFFFF output 我所做的
我有 Eclipse Indigo 版本,我可以在其中运行 Java 和 C++ 项目。 但我只想使用另一个 Eclipse 来编写 C++ 项目。所以我将 eclipse(不是工作区)的源文件夹复制
This question already has answers here: What is a NullPointerException, and how do I fix it? (12个答案)
This question already has answers here: Numbering rows within groups in a data frame (8个答案) 5个月前关闭。
我知道用q记录到寄存器中,但我想知道是否可以设置一些东西来快速调用最后一个记录,就像一样。 回顾最后一个简短的编辑命令(有关 的讨论请参阅 here。)。 我知道@@,但它似乎只有在执行@z之后才起作
来自 Eclipse 并且一直习惯于复制行,发现 Xcode 没有这样的功能是很奇怪的。或者是吗? 我知道可以更改系统范围的键绑定(bind),但这不是我想要的。 最佳答案 要删除一行:Ctrl-A
假设我有一个包含元素的列表,例如[1,2,3,4,5,6,7,8]。我想创建长度为 N 的该元素的所有排列。 因此,对于N = 4,它将是[[1,1,1,1],[1,1,1,2],[1,1,2,1],
我有一个带有 JMenu 的 JFrame。当我在某些情况下添加包含图像的 JPanel 时,程序首次启动时菜单会重复。调整大小时重复的菜单消失。任何建议都非常感激。谢谢。代码如下: public c
我正在尝试查找目录中文件的重复项。 我对这个 block 有一个问题,它以文件地址作为参数: public void findFiles(ArrayList list){ HashMap hm
我知道这个问题已经发布并且已经给出了答案,但我的情况不同,因为我在单个方法上填充多个下拉列表,所以如果我点击此链接 After every postback dropdownlist items re
我正在尝试为我的日历应用程序实现重复模式。我希望它的工作方式与 Outlook 在您设置重复约会时的工作方式相同。 public async Task> ApplyReccurrencePeriod
我有一个利用 cookie 来支持准向导的应用程序(即,它是一组相互导航的页面,它们必须以特定顺序出现以进行注册)。 加载 Logon.aspx 页面时 - 默认页面 - 浏览器 cookie 看起来
我有 3 个输入,代码检查它们是否为空,如果为空,则将变量值添加到输入中。 所以我有 3 个具有值的变量: var input1text = "something here"; var input2t
根据数组的长度更改数组的每个元素的最佳方法是什么? 例如: User #1 input = "XYZVC" Expected Output = "BLABL" User #2 input = "XYZ
我在让 Algolia 正常工作时遇到了一些麻烦。我正在使用 NodeJS 并尝试在我的数据库和 Algolia 之间进行一些同步,但由于某种原因似乎随机弹出大量重复项。 如您所见,在某些情况下,会弹
遵循以下规则: expr: '(' expr ')' #exprExpr | expr ( AND expr )+ #exprAnd | expr ( OR expr )+ #exprO
我有一个布局,我想从左边进入并停留几秒钟,然后我希望它从右边离开。为此,我编写了以下代码: 这里我在布局中设置数据: private void loadDoctor(int doctorsInTheL
我是一名优秀的程序员,十分优秀!