GNU-LIBC源码学习之strlen

通过分析GNU-LIBC的strlen源码,探讨优化字符串长度计算的方法,减少执行时间和提高效率。源码中利用字节对齐和特定条件判断快速定位结束符,适合在性能要求高的场景下使用。
摘要由CSDN通过智能技术生成

问题来源于一道很小的编程题,要求写出strlen的函数。
很来很容易

str为字符指针
    int cnt=0while(*str != '\0')
        cnt++;
    return cnt;

在vs2008上顺利执行,但是在题目系统中出问题
这里写图片描述
题目给的要求是
1000ms 10000K
那就是这种算法超时了,
想想算距离,除了这种计数方法,还有什么
还有就是两绝对地址相减,地址相减得到绝对值差/类型长度
所以修改代码为如下


    char* base=str;
    while(*str++);
    returnstr - base -1);

直接找到字符串的结束地址,然后首尾相减。
这种算法相对于前一种,少执行一个计数累加,并且随着字符串长度的增加,效果越好。
编译提交后,符合时间要求。

基于此,要研究一下GNU libc是怎么写这个函数的
不看不知道 一看吓一跳 先贴出源码吧

/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Written by Torbjorn Granlund (tege@sics.se),
   with help from Dan Sahlin (dan@sics.se);
   commentary by Jim Blandy (jimb@ai.mit.edu).

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值