gpt4 book ai didi

c - 连接字符串和数字的最佳方式是什么 - 使用 C 的性能?

转载 作者:行者123 更新时间:2023-11-30 16:44:17 24 4
gpt4 key购买 nike

请向下阅读新/上次更新部分。

我非常尝试编写具有良好性能的代码。

而且 php 解释器脚本 比我的 c 应用程序 更快。​​

我正在一个大循环中测试这个。我确信我的连接代码的速度很糟糕。当然可以像 php 脚本一样让它变得更好。

<小时/>

编译来源(c):

for(int count=1;count<=1000000;count++)
{
results=str_int("New Item",count);
}
<小时/>

str_int(...) 功能:

#1:

DATA_VALUE_String *str_int(DATA_VALUE_String *s1,DATA_VALUE_Int64 s2)
{
DATA_VALUE_String *result=malloc(sizeof(s1)+sizeof(s2)+2*sizeof(DATA_VALUE_String *));
snprintf(result,sizeof(s2)+sizeof(s2),"%s%d",s1,s2);
return result;
}

时间:0m0.135s

#2:

DATA_VALUE_String *str_int(DATA_VALUE_String *s1,DATA_VALUE_Int64 s2)
{
DATA_VALUE_String *result=malloc(sizeof(s1)+sizeof(s2)+2*sizeof(DATA_VALUE_String *));
DATA_VALUE_String *ss2;
ss2=malloc((sizeof(s2)+2)*sizeof(DATA_VALUE_String *));
sprintf(ss2,"%"PRId64,s2);
strcat(strcpy(result,s1),ss2);
return result;
}

时间:0m0.160s

<小时/>

但是 PHP 7.1.4 :0.081s

<?php
//$myArrays = [];
for($count=1;$count<=1000000;$count++)
{
$results="";
$results="New Item".$count;
}
//unset($myArrays);
?>

请帮助我使这个 c 文件更快...

我想让我的 C 代码变得更好。

php 在连接字符串、int 方面有更好的性能。但我的c代码和他们不一样。

怎样才能让它变得更好?

非常欣赏你。 :喜欢:

============

答案 1 的新更新:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>

void int64ToChar(char **mesg, int64_t num) {
//*mesg="..";
*(int64_t *)mesg = num;
}
int main()
{
int64_t num=4694;
char *nums=malloc(6*sizeof(char *));
int64ToChar(&nums,num);
printf("%s",nums);
return 0;
}

错误:段错误(核心转储)

<小时/>

性能不佳的最新/最新更新(C 与 PHP)

php(最新版本):http://codepad.org/9D26wLEA

$ time php arrays2.php
real 0m0.089s
user 0m0.086s
sys 0m0.004s
<小时/>

c:http://codepad.org/JmemaXOr

$ gcc arrays.c -o arrays -O3 -w
$ time ./arrays
real 0m0.131s
user 0m0.091s
sys 0m0.040s

如何使我的 C 文件变得更好?

最佳答案

您可以尝试在 C 中连接字符串,通过指针直接将第二个字符串添加到内存中第一个字符串的末尾。

 char* strConcat(char* str1,char* str2){
while (*str1) str1++;
do{
*str1++ = *str2++
}while (*str2);
return --str1; //return a pointer to the end of the new string
}

这将返回一个指向新连接字符串末尾的指针,因此您只需传递该指针即可继续连接到当前字符串。或者,如果不需要进一步连接,您可以维护指向连接字符串头部的指针。

关于c - 连接字符串和数字的最佳方式是什么 - 使用 C 的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com