gpt4 book ai didi

c++ - 初始化每个类成员时出现性能问题?

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:27 26 4
gpt4 key购买 nike

我认为这个 SO 问题是关于初始化的一般观点,它已经回答了很多问题:

Should constructor initialize all the data members of the class?

但是,当我的类有 100 个成员并且我使用 {} 命令初始化每个成员时,我没有发现任何关于可能的性能问题的信息,只是因为 Eclipse 警告我未初始化的成员:

Member 'foo' was not initialized in this constructor

我的问题:每次实例化此类时,对具有很多成员 [>50] 的类中的每个成员进行初始化是否会导致性能问题?

更新:由于第一条评论:我一般问。 Eclipse 在我的项目中警告我 9 次分成 4 个类!

最佳答案

这是我用 gcc 运行它的结果。

我用不同数量的类成员测试了它 [5 次并取平均值],但使用了 100'000'000 个类实例。

这有点棘手,因为我使用了最高优化级别 -O3,因此我不得不避免编译器优化代码。

有 100 个类(class)成员:

Initialized class members:      4'484 msec
Not initialized class members: 50 msec

有 25 名类(class)成员:

Initialized class members:      1'146 msec
Not initialized class members: 50 msec // as expected it didn't change

有 500 名类(class)成员:

Initialized class members:     22'129 msec
Not initialized class members: 50 msec // as expected it didn't change

我的结论是:

在正常情况下 - 没有当所有类成员都被初始化时,会出现显着的性能问题。对于在正常情况下,我的意思是当有一个函数[与其他代码] 有 100'000'000 次迭代时,成员初始化实际上不算数。

如评论中所述,一个好的设计不应该有这么多类(class)成员 - 我只是一般好奇。


附言:

我检查了汇编程序列表 - 当然 - 在初始化版本中 gcc 确实用 movq $0, 40(%rsp) 初始化了每个 int 成员 - 40 是栈上的位置。


#include <stdlib.h>
#include <stdio.h>
#include <chrono>
#include <ctime>
#include <utility>

template<typename TimeT = std::chrono::microseconds>
class measure
{
public:
template<typename F, typename ...Args>
static typename TimeT::rep execution(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);

return duration.count();
}
};

class foo
{
// for uninitialized version remove the {}
size_t mainValue {};
size_t classMember0 {};
...
size_t classMember499 {};

public:
foo( size_t value ) : mainValue (value + 4660) {};
auto getMainValue() -> size_t { return mainValue; };
};

auto runCode( size_t iterationCount ) -> void
{
size_t someValue {};
for ( size_t j = 0 ; j < iterationCount ; ++j )
{
foo MyFoo (iterationCount);
someValue += MyFoo.getMainValue();
}
printf( "Result=%ld\n", someValue ); // that the whole code isn't optimized away...
}

int main( int argc, char * argv [] )
{
if ( argc != 2 )
{
printf( "Usage: %s <Start-Value>\n", argv [0] );
return 0;
}

size_t variableValue = (size_t) atof( argv [1] );
auto threadExecutionTime = measure<>::execution( [&] () { runCode( variableValue ); } );

printf( "Total execution time was %.3f milliseconds. %s",
threadExecutionTime / 1000. );
}

关于c++ - 初始化每个类成员时出现性能问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com