You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的C++水仙花数程序运行速度仅为C版本的一半?

C++水仙花数程序运行速度仅为C程序一半的原因分析及解决办法

我分别用C和C实现了相同逻辑的水仙花数查找程序,通过bash脚本重复运行1000次并计时后,发现C程序的运行总耗时是C程序的两倍。以下是相关代码、测试步骤及最终的解决结论:

代码实现

C代码(main.c)

#include <stdio.h>
#include <stdbool.h>

bool is(int number)
{
    int s = number;
    int t = 0;
    while(number)
    {
        t += (number % 10) * (number % 10) * (number % 10);
        number /= 10;
    }
    return t == s;
}

int main()
{
    for(int i = 100; i < 1000; i++)
    {
        if(is(i))
        {
            printf("%d\n",i);
        }
    }
    return 0;
}

编译命令:

gcc main.c

C++代码(main.cpp)

#include <iostream>

using namespace std;

bool is(int number)
{
    int s = number;
    int t = 0;
    while(number)
    {
        t += (number % 10) * (number % 10) * (number % 10);
        number /= 10;
    }
    return t == s;
}

int main()
{
    for(int i = 100; i < 1000; i++)
    {
        if(is(i))
        {
            cout << i << endl;
        }
    }
    return 0;
}

编译命令:

g++ main.cpp

测试步骤

测试脚本(test.sh):

for i in {1..1000}; do ./a.out; done

计时命令:

time ./test.sh

原因分析与解决

通过静态编译后,两者的运行速度完全一致。推测问题根源在于动态链接的libstdc++库带来的启动开销:

  • 动态编译的C程序每次启动时,都需要加载并初始化libstdc库,这个过程的开销在重复1000次运行时被大幅放大;
  • C程序依赖的libc库通常系统缓存优化更好,或者其启动初始化开销远低于libstdc++;
  • 静态编译将libstdc++的相关代码直接打包进可执行文件,避免了每次启动时的库加载与解析开销,因此消除了两者的速度差异。

需要注意:如果是单次运行程序,两者的速度差异可能微乎其微,只有在高频重复启动的场景下,动态链接的开销才会凸显出来。

内容的提问来源于stack exchange,提问作者Karmylr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:50:29