[英]Working with large local arrays: is there a faster way than malloc?
I am working with large arrays in C for numerical calculations. 我正在使用C中的大型数组进行数值计算。
Within one of the functions I make use of some temporary local (disposable) arrays. 在其中一个函数中,我使用了一些临时的本地(一次性)数组。 Normally I would just declare these as double v[N]
and then not worry about having to free the memory manually. 通常,我只是将它们声明为double v[N]
,然后不必担心必须手动释放内存。
The problem that I have noticed is that when my N gets very large (greater than 4 million) my program fails to declare the variable. 我注意到的问题是,当我的N很大时(大于400万),我的程序无法声明该变量。 Hence I resorted to malloc()
and free()
which allows me to run the program successfully. 因此,我求助于malloc()
和free()
,使我能够成功运行程序。 The problem is that my execution time almost doubles from 24s to 40s when I use the dynamic allocation (for a smaller N). 问题是,当我使用动态分配时(对于较小的N),我的执行时间几乎从24s翻倍到40s。
It is possible for me to modify the code to avoid creating these temporary arrays in the first place, however it would impact on the readability of the code and coding effort. 我可以修改代码以避免一开始就创建这些临时数组,但是这会影响代码的可读性和编码工作。 I am currently using a preprocessor macro to access the vector like a 2D matrix. 我目前正在使用预处理器宏来像2D矩阵一样访问向量。 Is there another solution that will avoid the CPU cost whilst allowing me to save the data like a matrix? 是否有另一种解决方案可以避免CPU成本,同时又可以像矩阵一样保存数据?
When you declare a variable local to the method you are working with automatic allocated variables which go on the stack and unfortunately the stack size is limited. 当您声明方法局部变量时,您正在使用自动分配的变量,这些变量在堆栈上,但是不幸的是,堆栈大小受到限制。 Using malloc
means that the variable will be allocated on heap and the time difference is what you pay for that dynamic allocation. 使用malloc
意味着变量将在堆上分配,并且时差是您为该动态分配支付的时间。
I see two possible solutions: 我看到两种可能的解决方案:
static
global array (and reuse it when necessary) so that the compiler will be able to optimize accesses to it 使用static
全局数组(并在必要时重用),以便编译器能够优化对其的访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.