【发布时间】:2012-03-21 14:00:25
【问题描述】:
我将一个项目从 Visual C++ 6.0 移植到 VS 2010,发现代码的关键部分(脚本引擎)现在的运行速度比以前慢了大约三倍。 经过一些研究,我设法提取了似乎导致速度下降的代码片段。我尽可能将其最小化,因此更容易重现问题。 当分配一个包含另一个类(String)的复杂类(Variant)以及其他几个简单类型字段的联合时,该问题会重现。
玩这个例子我发现了更多的“魔法”: 1.如果我评论一个未使用的(!)类成员,速度会提高,并且代码最终运行得比那些遵循 VS 6.2 的要快 2.如果我删除“联合”包装器也是如此 3. 将字段的值从 1 更改为 0 也是如此
我不知道到底发生了什么。 我检查了所有代码生成和优化开关,但没有任何成功。
代码示例如下: 在我的 Intel 2.53 GHz CPU 上,这个测试在 VS 6.2 下编译运行 1.0 秒。 在 VS 2010 下编译 - 40 秒 在 VS 2010 下编译,注释“魔术”行 - 0.3 秒。
使用任何优化开关都会重现此问题,但应禁用“整个程序优化”(/GL)。否则这个太聪明的优化器会知道 out 测试实际上什么都不做,测试会运行 0 秒。
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
class String
{
public:
char *ptr;
int size;
String() : ptr(NULL), size( 0 ) {};
~String() {if ( ptr != NULL ) free( ptr );};
String& operator=( const String& str2 );
};
String& String::operator=( const String& string2 )
{
if ( string2.ptr != NULL )
{
// This part is never called in our test:
ptr = (char *)realloc( ptr, string2.size + 1 );
size = string2.size;
memcpy( ptr, string2.ptr, size + 1 );
}
else if ( ptr != NULL )
{
// This part is never called in our test:
free( ptr );
ptr = NULL;
size = 0;
}
return *this;
}
struct Date
{
unsigned short year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char minute;
unsigned char second;
unsigned char dayOfWeek;
};
class Variant
{
public:
int dataType;
String valStr; // If we comment this string, the speed is OK!
// if we drop the 'union' wrapper, the speed is OK!
union
{
__int64 valInteger;
// if we comment any of these fields, unused in out test, the speed is OK!
double valReal;
bool valBool;
Date valDate;
void *valObject;
};
Variant() : dataType( 0 ) {};
};
void TestSpeed()
{
__int64 index;
Variant tempVal, tempVal2;
tempVal.dataType = 3;
tempVal.valInteger = 1; // If we comment this string, the speed is OK!
for ( index = 0; index < 200000000; index++ )
{
tempVal2 = tempVal;
}
}
int main(int argc, char* argv[])
{
int ticks;
char str[64];
ticks = GetTickCount();
TestSpeed();
sprintf( str, "%.*f", 1, (double)( GetTickCount() - ticks ) / 1000 );
MessageBox( NULL, str, "", 0 );
return 0;
}
【问题讨论】:
标签: visual-studio-2010 code-generation