在读《深度探索C++对象模型》一书时,看到NRV(named return value)优化的说明,
觉得很有意思,于是写了一段小的代码,来测试下有NRV优化和无NRV优化有什么区别。
测试环境:Win7
编译软件: VS2008
说明:VS2008上Debug和Release版本已经天然区别开了NRV优化情况。
Debug版本无NRV优化,Release版本有NRV优化,因此,可以直接通过编译不同版本来进行测试。
(其实说白了,在NRV优化是由选项控制的,在Optimization中O1/O2都可以打开NRV优化,Od关闭NRV优化)
代码如下:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// teset.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "atltime.h" using namespace std; class test { friend test foo( double); public: test() { memset(array, 0, 10000 * sizeof( double)); } private: double array[ 10000]; }; test foo( double val) { test local; local.array[ 0] = val; local.array[ 99] = val; return local; } int _tmain( int argc, _TCHAR *argv[]) { CTime t = CTime::GetCurrentTime(); cout << t.GetHour() << ":" << t.GetMinute() << ":" << t.GetSecond() << endl; //start time for ( int i = 0; i < 10000000; i++) { test t = foo( double(i)); } t = CTime::GetCurrentTime(); cout << t.GetHour() << ":" << t.GetMinute() << ":" << t.GetSecond() << endl; //end time return 0; } |
16:46:45
16:48:28
请按任意键继续. . .
Release版本执行结果为:
16:48:55
16:48:55
请按任意键继续. . .
可以看到Debug版本需要102秒,而Release版本在1秒内就完成了,可以NRV优化后确实效果不错。
看到这里你可以还有疑问,Release版本不光优化了NRV,还有其他优化的。
没有关系,我们再做个试验,将O2开关关闭,再运行下Release版本,这里测试出的时间与Release打开O2开关的时间之差就大概是NRV优化后的执行时间。
测试结果如下:
Release版本去掉NRV优化执行时间:
16:53:24
16:54:33
请按任意键继续. . .
这里花了68秒。
68-1 = 67 秒,
就是说NRV优化大概节省了67秒的时间。
确实效果非常明显。