【发布时间】:2012-01-18 22:25:05
【问题描述】:
我正在使用scanf("%d", &someint) 对正整数进行大量解析。因为我想看看 scanf 是否是一个瓶颈,所以我使用fread 实现了一个简单的整数解析函数,就像:
int result;
char c;
while (fread(&c, sizeof c, 1, stdin), c == ' ' || c == '\n')
;
result = c - '0';
while (fread(&c, sizeof c, 1, stdin), c >= '0' || c <= '9') {
result *= 10;
result += c - '0';
}
return result;
但令我惊讶的是,这个函数的性能(即使有内联)大约差了 50%。不应该有可能改进 scanf 的特殊情况吗? fread 不应该很快吗(附加提示:整数是(edit: most)1 或 2 位数字)?
【问题讨论】:
-
你不是说
c >= '0' && c <= '9' -
scanf可能已被编译器优化。fread几乎肯定没有优化为使用 STDIN 作为输入。 -
至少你应该使用
fgetc... -
fread() 肯定不打算一次读取一个字符。大概甚至 fgetc() 表现更好。
-
从挑剔的角度来看,我建议使用
isdigit()而不是c>='0' && c<='9',因为数字可能并非在每个字符集中都是连续的,例如EBCDIC。
标签: c input scanf numeric-input