为什么这个简单的数学问题在 python 中比 C++ 更快

所以我在 python 和 C++ 中做了一个简单的 Collat​​z Conjecture 脚本,目的是为了好玩并测试两种语言的性能

C++ 平均需要 6.9 秒 而python需要0.3秒

我什至没有使用 numpy 或默认的 Python 函数

python 是不是更擅长简单的数学?

澄清 C++ 我只是使用 Visual Studio 和 c++ 版本是 c++ std 14

我不知道实际的编译选项

这是代码

c++ 代码

#include <iostream>
#include <chrono>

int main() {
    long long int num = 1; //i was messing around with this math problem so i made it a long long because i doing bigger numbers
    long long int i = num;

    auto begin = std::chrono::high_resolution_clock::now();
    while (num < 1000) {
        //if even
        if (i % 2 == 0) {
            i /= 2;
        }
        //if odd
        else {
            i *= 3;
            i += 1;
        }

        std::cout << i << std::endl;

        if (i == 1) {
            num++;

            std::cout << "num = " << num << std::endl;

            i = num;
        }

        if (i < 1) {
            break;
        }
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration<float>(end - begin);
    std::cout << elapsed.count() << std::endl;
    return 0;
}

python 代码

import time

def main():
    num = 1
    i = num

    start = time.time()
    while num < 1000:
        if i % 2 == 0:
            i /= 2

        else:
            i *= 3
            i += 1

        print(str(i) + "\n")

        if i == 1:
            num += 1
            print("num = " + str(num) + "\n")
            i = num

        if i < 1:
            break

    end = time.time()

    out = end - start

    print(out)

if __name__ == "__main__":
    main()
yukiww 回答:为什么这个简单的数学问题在 python 中比 C++ 更快

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/152.html

大家都在问