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



请向下阅读new/last update部分。

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

而且php interpreter script我的c app更快.

我正在一个大循环中测试这个。 而且我确信我的连接代码的速度很差。 当然,然后可以使它像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;
}

错误 :Segmentation fault (core dumped)


性能不佳的新更新/上次更新(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
}

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

有人给出了一种比 snprintf 快得多的算法,用于将 int 转换为字符串: 如何在 C 语言中将 int 转换为字符串

这个算法(我在下面命名为xitoa)也比PHP脚本更快。 (我用 int32 而不是 int64 进行了测试,但它说明了对 snprintf 的显着改进)

我的基准:

  • 使用SNprintf:1.54秒
  • 使用西托亚:0.99秒
  • 使用PHP:1.23秒

这些结果是使用 gcc 优化 -O2 获得的(对于 snprintf 和 xitoa)。

这是我测试的算法(从给定的链接复制):

char * xitoa (int value, char *buffer, int base)
{
// check that the base if valid
if (base < 2 || base > 36) { *buffer = ''; return buffer; }
char* ptr = buffer, *ptr1 = buffer, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '';
// reverse the characters, as they were stored less-significant first
while (ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return buffer;
}

最新更新