The pitfalls of C ++ years (Appendix 1), those years that have pitted us

Source: Internet
Author: User

The pitfalls of C ++ years (Appendix 1), those years that have pitted us
C ++ (Appendix 1)
Author: Liu Junyan (Alinshans) this series of articles aimed at various pitfalls I have stepped on when writing C ++ code, especially when I was working on my own projects. This serves as your own vigilance.

 

 

[Copyright statement] reprinted please indicate the original from: http://www.cnblogs.com/GodA/p/6639526.html

 

I started to write the script last month. It was not found until now. There are too many things. Some children may not know the cause of this essay, so you can take a look at what I wrote before.

At the end of the previous article, I mentioned a problem: code optimization. A small test is left: the performance of the unsigned number and the signed number is compared. I don't know if anyone has gone to the experiment. I did a simple test:

#include <iostream>#include <chrono>int main(){  /*unsigned */int a = 123456789;  auto t1 = std::chrono::system_clock::now();  for (int i = 0; i < 100; ++i)  {    a += 3;    a -= 5;    a *= 7;    a /= 7;  }  auto t2 = std::chrono::system_clock::now();  auto runtime = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1);  std::cout << "a = " << a <<"\n";  std::cout << runtime.count() << "ns";}

In the above CodeDebug modeRun the following command (the Release is optimized). After the stability is reached, the running time is 2800ns. Then, the comments are removed and run again. After the stability is reached, the running time is still 2800ns. On my computer, there is almost no difference in the calculation of the signed type and the unsigned type. I believe the results are the same on most computers.

Similarly, is floating point computing slower than integer computing? For this problem, you can take a look at this problem: https://www.zhihu.com/question/26494062.

First, I want to declare that I am not opposed to code optimization. There are many widely-spread so-called optimization techniques. I think we should keep learning and exploring, instead of simply pursuing something meaningless. Some optimizations are really subtle. However, many so-called tricks seem to mean that the people who make compilers are dumb. It is a normal idea to optimize our program, but we should use scientific methods, instead of listening to odd sex techniques, but do not know what happened in it.

In fact, it is very simple to explore performance bottlenecks depends on profiling, explore the unknown story behind the code to see assembly. Let's talk about the next one.

I think most people are still programming in Windows, so it must be the most powerful IDE VS in the universe. It is very easy to view the Assembly under VS. You can set a breakpoint at will, start debugging according to the debugging below, and find the disassembly In the debugging window. For example, to study the number of symbols and the number of unsigned, first write a program:

int main(){  /*unsigned */int a = 123456789;  a = a / 13;  std::cout << a;}

Then follow the method (Under Debug) View the disassembly:

  /*unsigned */int a = 123456789;00B4104E  mov         dword ptr [a],75BCD15h    a = a / 13;00B41055  mov         eax,dword ptr [a]  00B41058  cdq  00B41059  mov         ecx,0Dh  00B4105E  idiv        eax,ecx  00B41060  mov         dword ptr [a],eax  

Then try removing the comment:

  unsigned int a = 123456789;00C3104E  mov         dword ptr [a],75BCD15h    a = a / 13;00C31055  mov         eax,dword ptr [a]  00C31058  xor         edx,edx  00C3105A  mov         ecx,0Dh  00C3105F  div         eax,ecx  00C31061  mov         dword ptr [a],eax  

Almost identical. The biggest difference is that the idiv command (with the symbol Division) is used for the signed number, and the div command (without the symbol Division) is used for the unsigned number, the CPU cycle is the same. Http://www.agner.org/optimize/instruction_tables.pdf.

Of course, I'm not saying that we don't need to use the unsigned number, but that we need to look at the occasion, instead of thinking that the performance is better, unless it is recognized by the public or you have undergone rigorous tests. For some books or places, as long as the scope is determined not to be negative, the unsigned type is used. I do not recognize it. If you talk about the range, if a signed type is not enough, then the unsigned type corresponding to it is usually (in the same bit) is not enough. For example, if your int32_t is not enough, you should use int64_t. If not, consider writing a BigInteger class :). However, for unsigned and signed types, the performance between them is indeed almost identical in the contemporary era. What are the specific scenarios? This is not necessarily the case, for example:

  • For bit storage, bit operations, modulo operations, and so on, use the unsigned type
  • Use a signed type for general operations

In fact, I think there is something special about unsigned symbols .. We usually say that a number is either an integer or a decimal number, and whether there are symbols or not. But because it is C ++, There is nothing strange.

It seems a little different from the theme I want to talk about (drag back

I don't want to talk about this signed and unsigned question, but I want to use this question to give some comments:

  • Premature optimization is the source of all evil
  • Do not try to optimize the Compiler
  • During optimization, do not guess. take it for granted that you have to optimize what you "think" has poor performance.
  • Profiling is used to explore performance bottlenecks

Let's talk about it.

For a requirement, we should first complete the function. If the performance fails to meet the requirements, we should optimize the performance after determining the bottleneck. Early optimization not only makes the code less direct, but also easily produces bugs, and may have almost no impact on performance. In addition, we should pay attention to the general direction during optimization and make sure that the general direction is correct. For example, to write an algorithm, we should first make sure that the time complexity of Big-O is up to standard. O (n) is not required for O (nlogn), and O (nlogn) can be used) instead of using I ++ or ++ I. In addition, don't try to optimize the compiler, because the compiler is written by a bunch of people who do not know much about it than you do. for average people, they want to optimize the compiler, most of them are invalid, and a few are incorrect. For example, if someone has learned a little thing about std: move, they always want to move to improve performance. For example, it is easy to write (different) such code:

template <typename T>T create(){  auto object = new T();  return std::move(object);}

It is true that the operation will not be wrong, but the things behind the Code are not necessarily the same as you think, often different from what you think. In some cases, the compiler can adopt a better method. As a result, you are forced to use only one method at a time. Let's take a look at this question.
For example, if two variables are exchanged with an exclusive or, some people may think that bitwise operations not only do not need to create temporary variables, but bit operations are generally not faster! For this problem, Chen Shuo had mentioned earlier in Chapter 9th of https://cloud.github.com/downloads/chenshuo/documents/CppPractice.pdf. If you have not read it, go on your own.

If you have read the above link, then you will know that you (almost) will not know what the compiler has done, the optimization that the compiler can do is beyond your imagination (but sometimes it is obvious that the optimization compiler cannot do it, but it has little impact). In my series of articles (II) I have repeatedly stressed that you should not try to help the compiler to optimize it. If you want to explore the details behind a short piece of code, let's look at the disassembly!

Then I still want to post an answer about exploring performance bottlenecks: https://www.zhihu.com/question/56727144/answer/150555866

Finally, I hope all the links I put will be carefully read! Why do I post so many links? Because I have no authority, no one believes it! There is always a reference value for the great god! (

Okay, so much to write first.

Talent learning is not easy. If there are any improper places, please haihan. Thank you for your advice!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.