[英]Optimizing file write C
how can I improve speed while working with a file?如何在处理文件时提高速度? Here's my code:这是我的代码:
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int l, int r)
{
int i;
if (l == r) {
printf("%s\n", a);
FILE *fp;
fp = fopen("test.txt", "a");
fprintf(fp,"%s\n", a );
fclose(fp);
}
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
remove("test.txt");
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
char str[] = "ABCD";
int n = strlen(str);
permute(str, 0, n-1);
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
return 0;
}
If I run it saving the permutations to a file I get Total time = 0.161452 seconds
如果我运行它将排列保存到一个文件中,我得到Total time = 0.161452 seconds
Without saving permutations to a file I get Total time = 0.00000 seconds
在不将排列保存到文件的情况下,我得到Total time = 0.00000 seconds
Thanks!谢谢!
Basic optimizations:基本优化:
"w"
write to it and it will have the same effect.启动时不需要删除该文件,您也可以"w"
写入它,它会产生同样的效果。These will make a vast difference.这些将产生巨大的不同。 Opening a file takes lots of time, as does writing to it or removing it.打开文件需要花费大量时间,写入文件或删除文件也是如此。 Everything file-related are the main bottlenecks in this program.与文件相关的所有内容都是该程序的主要瓶颈。
As for the recursion, you have written a version that isn't likely tail-call optimized, so it will bloat up the stack needlessly.至于递归,您已经编写了一个不太可能优化尾调用的版本,因此它会不必要地膨胀堆栈。
Advanced optimizations:高级优化:
Micro-optimizations (will only have a small effect):微优化(只会产生很小的影响):
strlen
with sizeof
.将strlen
替换为sizeof
。printf
/ fprintf
with puts
/ fputs
.将printf
/ fprintf
替换为puts
/ fputs
。restrict
qualify the pointers in swap
(probably not needed since it should get inlined). restrict
限定swap
中的指针(可能不需要,因为它应该被内联)。 Try open/close file only once, in the main()
function, like below:在main()
函数中只尝试打开/关闭文件一次,如下所示:
void permute(char *a, int l, int r, FILE *fp)
{
int i;
if (l == r)
{
printf("%s\n", a);
fprintf(fp, "%s\n", a);
}
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r, fp);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
remove("test.txt");
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
char str[] = "ABCD";
int n = strlen(str);
// open file
FILE *fp;
fp = fopen("test.txt", "a");
permute(str, 0, n-1, fp);
// close file
fclose(fp);
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.