码迷,mamicode.com
首页 > 其他好文 > 详细

常数优化那点事

时间:2016-08-07 18:38:11      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

(被各位神犇的代码所虐,故设此文)

(纯经验之谈,如能指出其原理或谬误,欢迎留言)

测试环境:

OS:Linux Ubuntu 14.04LTS 

Memory:8GB

Processor:Intel® Core™ i7-4500U CPU @ 1.80GHz × 4 

Compiler:GNU G++ 4.8.4(switch on -O3 optimization in release mode)

Part I:输入(若无特殊说明,输入类型为int,scanf每执行一次只接收一个参数)

C++ iostream的优化语句(使用后要避免C++ IO和C-style IO混用):

std::ios::sync_with_stdio(0);

std::cin.tie(0);

不加以上优化时std::cin的耗时约为scanf的4倍(不管是否开启-Ox编译优化)

加上优化后的耗时与scanf相当

读入优化在不开-Ox时与scanf相比并没有优势,开-Ox后比scanf快10%~15%

而scanf的速度似乎与一次接收的参数个数有关,输入量一定时,一次读5个的用时比一次读1个快10%~15%,且不受编译优化开关影响

技术分享
 1 #include <iostream>
 2 #include <cctype>
 3 #include <initializer_list>
 4 
 5 #if __cplusplus < 201103L
 6 #include <bits/c++0x_warning.h>
 7 #endif // __cplusplus
 8 
 9 template <class IstreamType, class IntType>
10 void _read_positive_integer (IstreamType& ist, IntType& dest)
11 {
12     dest = 0;
13     char ch = ist.get();
14     while (!isdigit (ch)) ch = ist.get();
15     while (isdigit (ch))
16     {
17         dest *= 10;
18         dest += ch - 0;
19         ch = ist.get();
20     }
21 }
22 
23 template <class IstreamType, class IntType>
24 void _read_integer (IstreamType& ist, IntType& dest)
25 {
26     dest = 0;
27     char ch = ist.get();
28     while (!isdigit (ch) && ch != -) ch = ist.get();
29     if (ch == -)
30     {
31         ch = ist.get();
32         while (isdigit (ch))
33         {
34             dest *= 10;
35             dest -= ch - 0;
36             ch = ist.get();
37         }
38     }
39     else while (isdigit (ch))
40         {
41             dest *= 10;
42             dest += ch - 0;
43             ch = ist.get();
44         }
45 }
46 
47 template <class IstreamType, class IntType, class... Args>
48 inline void readPositiveInteger (IstreamType& ist, IntType& first,
49                                  Args& ... args)
50 {
51     std::initializer_list<int> dummy =
52     { (_read_positive_integer (ist, first), 0), (_read_positive_integer (ist, args), 0)... };
53 }
54 
55 template <class IstreamType, class IntType, class... Args>
56 inline void readInteger (IstreamType& ist, IntType& first, Args& ... args)
57 {
58     std::initializer_list<int> dummy =
59     { (_read_integer (ist, first), 0), (_read_integer (ist, args), 0)... };
60 }
Input optimization with C++ style input

 

 

————To be continued————

常数优化那点事

标签:

原文地址:http://www.cnblogs.com/Onlynagesha/p/5746655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!