【发布时间】:2013-10-01 15:19:09
【问题描述】:
我正在尝试提高我的程序的性能(在 ARC 平台上运行,使用 arc-gcc 编译。话虽如此,我并不期待特定于平台的答案)。
我想知道以下哪种方法更优化以及为什么。
typedef struct _MY_STRUCT
{
int my_height;
int my_weight;
char my_data_buffer[1024];
}MY_STRUCT;
int some_function(MY_STRUCT *px_my_struct)
{
/*Many operations with the structure members done here*/
return 0;
}
void poorly_performing_function_method_1()
{
while(1)
{
MY_STRUCT x_struct_instance = {0}; /*x_struct_instance is automatic variable under WHILE LOOP SCOPE*/
x_struct_instance.my_height = rand();
x_struct_instance.my_weight = rand();
if(x_struct_instance.my_weight > 100)
{
memcpy(&(x_struct_instance.my_data_buffer),"this is just an example string, there could be some binary data here.",sizeof(x_struct_instance.my_data_buffer));
}
some_function(&x_struct_instance);
/******************************************************/
/* No need for memset as it is initialized before use.*/
/* memset(&x_struct_instance,0,sizeof(x_struct_instance));*/
/******************************************************/
}
}
void poorly_performing_function_method_2()
{
MY_STRUCT x_struct_instance = {0}; /*x_struct_instance is automatic variable under FUNCTION SCOPE*/
while(1)
{
x_struct_instance.my_height = rand();
x_struct_instance.my_weight = rand();
if(x_struct_instance.my_weight > 100)
{
memcpy(&(x_struct_instance.my_data_buffer),"this is just an example string, there could be some binary data here.",sizeof(x_struct_instance.my_data_buffer));
}
some_function(&x_struct_instance);
memset(&x_struct_instance,0,sizeof(x_struct_instance));
}
}
在上面的代码中,poorly_performing_function_method_1() 性能更好还是poorly_performing_function_method_2() 性能更好?为什么?
需要考虑的事情很少..
- 在方法 #1 中,结构内存的重新分配、重新分配是否会增加更多开销?
- 在方法#1 中,在初始化期间,是否进行了优化?喜欢calloc(优化内存分配和在零填充页面中分配内存)?
我想澄清一下,我的问题更多是关于 WHICH 方法更优化,而不是关于如何使此代码更优化。此代码只是一个示例。
关于使上述代码更优化,@Skizz 给出了正确答案。
【问题讨论】:
-
我不熟悉 ARC - 是否有任何特定于平台的东西会阻止您对其进行基准测试?
-
@us2012 更新了问题。不,我不是在查看特定于平台的答案。只是为了完成而提到的平台。
-
使用memset()的函数,性能会下降,因为memset是高成本的内存操作
-
@CCoder:你分析过它吗?
-
@nneonneo 是的。我已经使用 oprofile 对其进行了分析,我看到 memset 出现在方法 2 的列表中。但我不确定方法 1 是否提供了更好的整体性能,因为我在分析期间运行了许多其他代码。
标签: c linux performance