« 一次简单C程序的性能优化 »
Developer » http://www.anysql.net/developer/simple-c-program-tuning.html 2009-10-27下面这段简单的程序, 如何优化?
#include <stdio.h>
void main ()
{
int i;
for (i=0;i<20000000;i++)
{
printf(“%012d\n”,i);
}
}
下午居然想到要来优化这段程序, 并且写出了更好的程序, 性能提升了30%, 从18秒提升到了12秒.
#include <stdio.h>
typedef struct _NUMERLIST
{
int len;
char buf[5];
} NUMBERLIST;void printNumber(int num, NUMBERLIST numlist[])
{
int v_num,i,j,k,pos=0;
char tmpbuf[32];
memset(tmpbuf,0,32);
v_num=num;
for(i=3;i>=0;i–)
{
v_num = num;
for(k=0;k<i;k++) v_num = v_num/1000;
v_num = v_num % 1000;
if (v_num > 999)
pos = pos + sprintf(tmpbuf+pos,”%03d”, v_num);
else
{
memcpy(tmpbuf+pos, numlist[v_num].buf,3);
pos = pos + 3;
}
}
printf(“%s\n”, tmpbuf);
}void main ()
{
NUMBERLIST numlist[1000];
int i;
for (i=0;i<1000;i++)
{
sprintf(numlist[i].buf, “%03d”, i);
}
for (i=0;i<20000000;i++)
{
printNumber(i, numlist);
}
}
如果优化一下两个程序的IO, 采用缓冲输出, 估计第二段程序更显优势.


作者有够无聊
有心呀!
我的测试结果,如果不重定向,时间就会全用在显示上
D:\app>cl p.c /O2
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80×86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
p.c
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation. All rights reserved.
/out:p.exe
p.obj
D:\app>cl p1.c /O2
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80×86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
p1.c
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation. All rights reserved.
/out:p1.exe
p1.obj
D:\app>t
D:\app>time 0p 1>p.log
D:\app>time 0p1 1>p1.log
D:\app>time 0
当前时间: 13:15:34.40
输入新时间:
D:\app>p 1>p.log
D:\app>time 0
当前时间: 13:15:42.52
输入新时间:
D:\app>p1 1>p1.log
D:\app>time 0
当前时间: 13:15:48.62
如果p2.c
typedef struct _NUMERLIST
{
char buf[4];
} NUMBERLIST;
D:\app>time 0
当前时间: 13:30:15.31
输入新时间:
D:\app>p2 1>p.log
D:\app>time 0
当前时间: 13:30:21.43
输入新时间:
D:\app>p1 1>p1.log
D:\app>time 0
当前时间: 13:30:28.81
输入新时间: