为什么锁定会降低此顺序文件解析器的速度?

cls*_*udt 6 c++ locking pthreads c++11

我为图形文件格式编写了一个简单的阅读器和解析器.问题是它非常慢.以下是相关方法:

Graph METISGraphReader::read(std::string path) {
    METISParser parser(path);
    std::pair<int64_t, int64_t> header = parser.getHeader();
    int64_t n = header.first;
    int64_t m = header.second;

    Graph G(n);

    node u = 0;
    while (parser.hasNext()) {
        u += 1;
        std::vector<node> adjacencies = parser.getNext();
        for (node v : adjacencies) {
            if (! G.hasEdge(u, v)) { 
                G.insertEdge(u, v);
            }
        }
    }
    return G;
}

std::vector<node> METISParser::getNext() {
    std::string line;
    bool comment = false;
    do {
        comment = false;
        std::getline(this->graphFile, line);
        // check for comment line starting with '%'
        if (line[0] == '%') {
            comment = true;
            TRACE("comment line found");
        } else {
            return parseLine(line);
        }

    } while (comment);
}

static std::vector<node> parseLine(std::string line) {
    std::stringstream stream(line);
    std::string token;
    char delim = ' ';
    std::vector<node> adjacencies;

    // split string and push adjacent nodes
    while (std::getline(stream, token, delim)) {
        node v = atoi(token.c_str());
        adjacencies.push_back(v);
    }
    return adjacencies;
}
Run Code Online (Sandbox Code Playgroud)

为了诊断它为什么这么慢,我在一个分析器(Apple Instruments)中运行它.结果令人惊讶:由于锁定开销,它很慢.该项目花费的它在时间上超过90%pthread_mutex_lock_pthread_cond_wait.

仪器

我不知道锁定开销来自哪里,但我需要摆脱它.你能建议下一步吗?

编辑:查看扩展的调用堆栈_pthread_con_wait.通过查看这个,我无法弄清楚锁定开销的来源:

在此输入图像描述

kar*_*ski 2

展开 _pthread_cond_wait 和 pthread_mutex_lock 调用的调用堆栈,以找出调用锁定调用的位置。

作为猜测,我会说它存在于您正在执行的所有不必要的堆分配中。堆是线程安全的资源,在此平台上,可以通过互斥体提供线程安全。

  • 对象位于堆栈上,但这些集合从默认分配器为其内容分配存储,默认分配器从堆分配内存。 (2认同)