gpt4 book ai didi

c++ - 如何使我的动态数组或 vector 以与标准数组相似的速度运行? C++

转载 作者:行者123 更新时间:2023-11-30 03:57:25 24 4
gpt4 key购买 nike

我在 C++ 方面仍然缺乏经验,我正在尝试编写求和代码以精确地添加数字。这是一些有限差分软件的 dll 插件,代码在运行期间被调用了数百万次。我想编写一个函数,可以传入任意数量的参数并返回总和。我的代码如下所示:

#include <cstdarg>

double SumFunction(int numArgs, ...){ // this allows me to pass any number
// of arguments to my function.
va_list args;
va_start(args,numArgs); //necessary prerequisites for using cstdarg

double myarray[10];
for (int i = 0; i < numArgs; i++) {
myarray[i] = va_arg(args,double);
} // I imagine this is sloppy code; however i cannot create
// myarray{numArgs] because numArgs is not a const int.
sum(myarray); // The actual method of addition is not relevant here, but
//for more complicated methods, I need to put the summation
// terms in a list.

vector<double> vec(numArgs); // instead, place all values in a vector
for (int i = 0; i < numArgs; i++) {
vec.at(i) = va_arg(args,double);
}
sum(vec); //This would be passed by reference, of course. The function sum
// doesn't actually exist, it would all be contained within the
// current function. This is method is twice as slow as placing
//all the values in the static array.

double *vec;
vec = new double[numArgs];
for (int i = 0; i < (numArgs); i++) {
vec[i] = va_arg(args,double);
}
sum(vec); // Again half of the speed of using a standard array and
// increasing in magnitude for every extra dynamic array!

delete[] vec;
va_end(args);
}

所以我遇到的问题是,使用过大的静态数组是草率的编程,但使用 vector 或动态数组会大大降低程序速度。所以我真的不知道该怎么办。请问有人可以帮忙吗?

最佳答案

加快代码速度(代价是使其变得更复杂)的一种方法是在调用之间重用动态数组或 vector ,这样就可以避免每次调用函数时产生内存分配和释放的开销。

例如,在您的函数外将这些变量声明为全局变量或某个类中的成员变量。为了便于解释,我将它们设为全局变量:

double* sumArray = NULL;
int sumArraySize = 0;

在您的 SumFunction 中,检查数组是否存在,如果不存在则分配它,并在必要时调整大小:

double SumFunction(int numArgs, ...){ // this allows me to pass any number 
// of arguments to my function.
va_list args;
va_start(args,numArgs); //necessary prerequisites for using cstdarg

// if the array has already been allocated, check if it is large enough and delete if not:
if((sumArray != NULL) && (numArgs > sumArraySize))
{
delete[] sumArray;
sumArray = NULL;
}

// allocate the array, but only if necessary:
if(sumArray == NULL)
{
sumArray = new double[numArgs];
sumArraySize = numArgs;
}

double *vec = sumArray; // set to your array, reusable between calls
for (int i = 0; i < (numArgs); i++) {
vec[i] = va_arg(args,double);
}
sum(vec, numArgs); // you will need to pass the array size

va_end(args);

// note no array deallocation
}

要注意的是,您需要记住在某个时候通过调用与此类似的函数来释放数组(就像我说的那样,您需要为速度付出额外的复杂性):

void freeSumArray()
{
if(sumArray != NULL)
{
delete[] sumArray;
sumArray = NULL;
sumArraySize = 0;
}
}

您可以对 vector 采用类似(且更简单/更清晰)的方法,如果它不存在则在第一次分配它,或者如果它存在则使用 numArgs 对其调用 resize()。

关于c++ - 如何使我的动态数组或 vector 以与标准数组相似的速度运行? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28008491/

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