fputs 与 fprintf 和 double [英] fputs vs. fprintf and double

查看:57
本文介绍了fputs 与 fprintf 和 double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将双精度值放入文件中.因此,对于我的所有其他字符串,我必须使用 fputs,因为我认为 fputs 比 fprintf 更快.

I need to put out a double value into an file. So for all my other string i have to put out i use fputs because i think and timed it that fputs is faster then fprintf.

但是如果我想输出双精度值,我不能用 fputs 来做到这一点,所以我尝试了 fprintf.这是非常缓慢的.如果我替换 fprintf 并在那里放一个 fputs("TEST",file);

But if i want to put out the double value i can't do this with fputs so i tried fprintf. This is very slow. I need more time if i replace the fprintf and puts there an fputs("TEST",file);

我怎样才能像字符串一样快地输出双倍.我需要先把它转换成字符串吗?

How can i put out the double as fast as the string. Need i to convert it first to string?

我发现了一些转换.但是如果我使用它们,我会像使用 fprintf 一样慢.

I found some conversion. But if i use them i am as slow as if i use the fprintf.

那么我怎样才能像向文件中放入字符串一样快速地将双精度数放入文件中?

So how can i put out the double to a file so fast as if i put out a string to the file?

  fputs("TEST",fileout); //FAST
  fprintf(fileout, "%f",p); //SLOW

使用 fprintf 双倍的时间:

Times with fprintf double:

END.PROCESSING.DATA: 2013-04-26 08:10:33.000
END.CALC.IN.FILE: 2013-04-26 08:11:13.000

使用 fputs 字符串的次数:

Times with fputs strings:

END.PROCESSING.DATA: 2013-04-26 08:14:10.000
END.CALC.IN.FILE: 2013-04-26 08:14:37.000

那个时候的代码:

now = time (0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("END.PROCESSING.DATA: %s\n", buff);

//output file
FILE *fileout;
fileout = fopen("out.txt","w");
double p;
for(i=0; i<17000;i++){
  for(j=0; j<i;j++){
    for(z=0;z<400;z++){
      //DO SOME WORK
    }
    p = 1.0;
    fputs(allsubsts[i],fileout);
    fputs(";",fileout);
    fputs(allsubsts[j],fileout);
    fputs(";",fileout);
    //fprintf(fileout, "%.21g", p);
    fputs("TEST",fileout);
    fputs(";\n",fileout);
  }
}
fclose(fileout);

now = time(0);
strftime(buff,100,"%Y-%m-%d %H:%M:%S.000", localtime(&now));
printf("END.CALC.IN.FILE: %s\n",buff);

时间之间的变化只是我把双倍而不是TEST字符串放在文件中的变化.

Changes between the time are only the change that i put the double instead the TEST string in the file.

推荐答案

将浮点数转换为十进制表示从根本上说是一个缓慢的操作.您可以尝试使用 %a 说明符代替 %f 将其存储为十六进制浮点数;这应该更快,并且可以安全地保留原始值而不是糟糕的近似值.如果你需要十进制,你应该使用 %.21g 或类似的,而不是 %f,因为后者会失去大部分精度.

Converting a floating point number to a decimal representation is a fundamentally slow operation. You might try using the %a specifier instead of %f to store it as a hex float; this should be much faster and would safely preserve the original value rather than a poor approximation. If you need decimal, you should be using %.21g or similar, not %f, as the latter will lose most of the precision.

如果这些对您来说都不够快,那么您可能需要直接保存值的二进制表示.

If none of this is fast enough for you, then you probably need to save the binary representation of the value directly.

这篇关于fputs 与 fprintf 和 double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆