Unusual Speed Difference between Python and C++

后端 未结 17 2326
庸人自扰
庸人自扰 2020-12-22 21:25

I recently wrote a short algorithm to calculate happy numbers in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it.

17条回答
  •  没有蜡笔的小新
    2020-12-22 21:49

    It looks like you're passing vectors by value to other functions. This will be a significant slowdown because the program will actually make a full copy of your vector before it passes it to your function. To get around this, pass a constant reference to the vector instead of a copy. So instead of:

    int sum(vector given)

    Use:

    int sum(const vector& given)

    When you do this, you'll no longer be able to use the vector::iterator because it is not constant. You'll need to replace it with vector::const_iterator.

    You can also pass in non-constant references, but in this case, you don't need to modify the parameter at all.

提交回复
热议问题