C++ inline 函数并不能降低程序运行时间

本文通过对比内联函数与普通函数在大量重复调用场景下的执行时间,发现内联函数并未如预期提升程序效率。实验代码使用C++实现,通过clock()函数测量时间,结果表明内联函数优化在特定条件下可能无效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<time.h>

inline double power1(double x,double y)
{
    return x*x+y*y;
}

double power2(double x,double y)
{
    return x*x+y*y;
}

int main(){

    clock_t time_start1,time_end1;
    LONG64 cnt=0;
    LONG64 cnt_max=900000000^2;
    time_start1=clock();
    for (cnt=0;cnt<cnt_max;cnt++)
    {
        power1(5.2,45.2);
    }
    time_end1=clock();
    std::cout<<"inline function time:"<<double(time_end1-time_start1)/CLOCKS_PER_SEC<<"s"<<std::endl;
    clock_t time_start2,time_end2;
    time_start2=clock();
    for (cnt=0;cnt<cnt_max;cnt++)
    {
        power2(5.2,45.2);
    }
    time_end2=clock();
    std::cout<<"No inline function time:"<<double(time_end2-time_start2)/CLOCKS_PER_SEC<<"s"<<std::endl;
    return 0;
}


程序运行结果看:Inline 处理并不能提高程序的时间执行效率。

问题出在哪里呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值