快速检验NRV优化测试代码

在读《深度探索C++对象模型》一书时,看到NRV(named return value)优化的说明,

觉得很有意思,于是写了一段小的代码,来测试下有NRV优化和无NRV优化有什么区别。

测试环境:Win7

编译软件: VS2008

说明:VS2008上Debug和Release版本已经天然区别开了NRV优化情况。

Debug版本无NRV优化,Release版本有NRV优化,因此,可以直接通过编译不同版本来进行测试。

(其实说白了,在NRV优化是由选项控制的,在Optimization中O1/O2都可以打开NRV优化,Od关闭NRV优化)


代码如下:

 C++ Code 
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,  010000 *  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;
}
Debug版本执行结果为:

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秒的时间。

确实效果非常明显。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值