首页 > 解决方案 > 尽管执行完全相同的操作,为什么双 while 循环比单个 while 循环执行得更快?

问题描述

“ptr”指向内存映射文件(wavefront .obj)

const char* ptr = data;
while (*ptr != '\0') {
    while (*ptr != '\0') {
        if (*ptr == 'v') {
            ptr++;
            if (*ptr == ' ') {
                vertex_count++;
                ptr += 27;
            }
            else if (*ptr == 't') {
                tex_coord_count++;
                ptr += 18;
            }
            else if (*ptr == 'n') {
                normal_count++;
                ptr += 21;
            }
        }
        else if (*ptr == 'f') {
            ptr++;
            if (*ptr == ' ') {
                index_count += 3;
                ptr += 17;
            }
        }
        ptr++;
    }
}
printf("v == %i\nvt == %i\nvn == %i\nf == %i\n", vertex_count, tex_coord_count, normal_count, index_count);

这个函数需要 490 毫秒到 520 毫秒来执行,而这个

const char* ptr = data;
while (*ptr != '\0') {
    if (*ptr == 'v') {
        ptr++;
        if (*ptr == ' ') {
            vertex_count++;
            ptr += 27;
        }
        else if (*ptr == 't') {
            tex_coord_count++;
            ptr += 18;
        }
        else if (*ptr == 'n') {
            normal_count++;
            ptr += 21;
        }
    }
    else if (*ptr == 'f') {
        ptr++;
        if (*ptr == ' ') {
            index_count += 3;
            ptr += 17;
        }
    }
    ptr++;
}
printf("v == %i\nvt == %i\nvn == %i\nf == %i\n", vertex_count, tex_coord_count, normal_count, index_count);

从 580 毫秒开始,一直到 610 毫秒。这背后有什么原因吗?

我正在为调试器使用带有 Release x64 配置的 VS2017,结果似乎非常一致。

标签: c++parsing

解决方案


推荐阅读