我有一个串行内存二维数组的类,它最初是一个 int
的数组。秒。现在我需要一个类似的另一种类型的数组,我用模板重写了这个类;唯一的区别在于存储对象的类型:
template <class T>
class Serial2DArray
{
...
T ** Content;
}
我有几个处理内容的测试函数,例如,一个使数组中的所有元素无效的函数(它们不是类成员,它们是处理 Serial2DArray<int>
对象的外部函数。我注意到现在它的工作速度慢了 1-2% - 类中的所有其他代码都没有受到影响,唯一的区别是之前它只是一个带有 int ** Content
的常规类,现在它是一个模板。
类似的问题:Do c++ templates make programs slow? - 认为只有编译变慢(我明白为什么,编译器会为它在代码中找到的每个类生成类),但在这里我看到程序在运行时变慢了 - 有任何合理的解释吗?
更新:问题在这里缩小了一点:https://stackoverflow.com/a/11058672/1200000
Upd2:如评论中所述,这是变慢的功能:
#include <windows.h>
#include <mmsystem.h>
...
int Size = G_Width * G_Height * sizeof(int);
DWORD StartTime = timeGetTime();
for(int i=0; i<100; ++i)
{
FillMemory(TestArray.Content[0], Size, 0);
}
MeasuredTime = timeGetTime() - StartTime;
这是实际的类模板:
#include <malloc.h>
template <class T>
class Serial2DArray
{
public:
Serial2DArray()
{
Content = NULL;
Width = 0;
Height = 0;
}
Serial2DArray(int _Width, int _Height)
{
Initialize(_Width, _Height);
}
~Serial2DArray()
{
Deinitialize();
}
T ** Content;
int GetWidth()
{
return Width;
}
int GetHeight()
{
return Height;
}
int Initialize(int _Width, int _Height)
{
// creating pointers to the beginning of each line
if((Content = (T **)malloc(_Height * sizeof(T *))) != NULL)
{
// allocating a single memory chunk for the whole array
if((Content[0] = (T *)malloc(_Width * _Height * sizeof(T))) != NULL)
{
// setting up line pointers' values
T * LineAddress = Content[0];
for(int i=0; i<_Height; ++i)
{
Content[i] = LineAddress; // faster than Content[i] =
LineAddress += _Width; // Content[0] + i * _Width;
}
// everything went ok, setting Width and Height values now
Width = _Width;
Height = _Height;
// success
return 1;
}
else
{
// insufficient memory available
// need to delete line pointers
free(Content);
return 0;
}
}
else
{
// insufficient memory available
return 0;
}
}
int Resize(int _Width, int _Height)
{
// deallocating previous array
Deinitialize();
// initializing a new one
return Initialize(_Width, _Height);
}
int Deinitialize()
{
// deleting the actual memory chunk of the array
free(Content[0]);
// deleting pointers to each line
free(Content);
// success
return 1;
}
private:
int Width;
int Height;
};
根据要求,二进制文件大小比较。
代码如下:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
- 1 016 832 字节。
代码如下:
Serial2DArray TestArray; // NOT-template class with ints
Serial2DArray ZeroArray; // methods are in class declaration
- 1 016 832 字节
代码如下:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
Serial2DArray<double> AnotherArray;
Serial2DArray<double> YetAnotherArray;
- 1 017 344 字节
最佳答案
是的 - 随机基准可变性,更不用说 整个程序 较慢的事实可能与这个特定类完全无关。
关于c++ - 用模板重写的类会使程序变慢(在运行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058431/