加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

开学了,出个题消遣下

(2012-02-20 10:56:35)
标签:

杂谈

linux提供的读文件函数,如果读一个较大的文件,总会间隔的出现行读变慢的情况。这是什么原因呢?怎么避免呢?呵呵。第一个完整答对者,我在微博上加他一声大哥吧(我可出不起iphone哦)。奖励只限在校学生哦。

例如:注意第1460行和1487行的耗时
1458th   the time cost for read a line 164
1459th   the time cost for read a line 844
1460th   the time cost for read a line 6016
1461th   the time cost for read a line 232
1462th   the time cost for read a line 232
1463th   the time cost for read a line 240
1464th   the time cost for read a line 192
1465th   the time cost for read a line 788
1466th   the time cost for read a line 264
1467th   the time cost for read a line 392
1468th   the time cost for read a line 176
1469th   the time cost for read a line 276
1470th   the time cost for read a line 324
1471th   the time cost for read a line 312
1472th   the time cost for read a line 252
1473th   the time cost for read a line 260
1474th   the time cost for read a line 196
1475th   the time cost for read a line 292
1476th   the time cost for read a line 356
1477th   the time cost for read a line 260
1478th   the time cost for read a line 284
1479th   the time cost for read a line 208
1480th   the time cost for read a line 344
1481th   the time cost for read a line 316
1482th   the time cost for read a line 304
1483th   the time cost for read a line 356
1484th   the time cost for read a line 264
1485th   the time cost for read a line 268
1486th   the time cost for read a line 224
1487th   the time cost for read a line 5276
1488th   the time cost for read a line 380
1489th   the time cost for read a line 332
1490th   the time cost for read a line 328


以下为实验代码

#include <stdio.h>
#include <stdlib.h>
#if defined(__i386__)

static __inline__ unsigned long long rdtsc(void)
{
  unsigned long long int x;
     __asm__ volatile ("rdtsc" : "=A" (x));
     return x;
}
#elif defined(__x86_64__)
static __inline__ unsigned long long rdtsc(void)
{
  unsigned hi, lo;
  __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
  return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}

#endif

int main(void)
{
        FILE * fp;
        char * line = NULL;
        size_t len = 0;
        ssize_t read;

        fp = fopen("./some_file_with_many_line", "r");
        if (fp == NULL)
                exit(EXIT_FAILURE);
        int start;
        int end;
        int i=0;
        start = rdtsc();
        while ((read = getline(&line, &len, fp)) != -1) {
                end = rdtsc();
                printf("%dth\t the time cost for read a line %d\n",i++,end - start);
                start = rdtsc();
        }
        if (line)
                free(line);
        exit(EXIT_SUCCESS);
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有