【发布时间】:2017-06-16 18:57:32
【问题描述】:
请下去阅读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 在连接 string,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 文件更好?
【问题讨论】:
-
“请帮助我,不要关闭问题。” ,这是题外话,您可能会在code review stack exchange 上获得更多运气。
-
我只是问了一个问题,那么如何才能做得更好?!
-
我怀疑你使用的是Shlemiel's algorithm,也许是
strcat()? -
意思是使用
strcat()?那么如何使用strcat()将 int 附加到 char* 以提高性能? -
sizeof(s1)并不像您认为的那样 - 它返回指针的大小,而不是您需要将字符串复制到的缓冲区的大小。我什至不完全确定这个表达式的 intent 是什么:sizeof(s1)+sizeof(s2)+2*sizeof(DATA_VALUE_String *)。在您过分担心性能之前,请确保代码正确。
标签: c string performance