OpenMP and File I/O

南笙酒味 提交于 2019-12-24 00:20:02

问题


I'm doing some time trials on my code, and logically it seems really easy to parallelize with OpenMP as each trial is independent of the others. As it stands, my code looks something like this:

for(int size = 30; size < 50; ++size) {
    #pragma omp parallel for
    for(int trial = 0; trial < 8; ++trial) {
        time_t start, end;
        //initializations
        time(&start);

        //perform computation

        time(&end);

        output << size << "\t" << difftime(end,start) << endl;
    }
    output << endl;
}

I have a sneaking suspicion that this is kind of a faux pas, however, as two threads may simultaneously write values to the output, thus screwing up the formatting. Is this a problem, and if so, will surrounding the output << size << ... code with a #pragma omp critical statement fix it?


回答1:


Never mind whether your output will be screwed up (it likely will). Unless you're really careful to assign your OpenMP threads to different processors that don't share resources like memory bandwidth, your time trials aren't very meaningful either. Different runs will be interfering with each other.

The solution to the problem you're asking about is to write the result times into designated elements of an array, with one slot for each trial, and ouput the results after the fact.




回答2:


As long as you don't mind the individual lines being out of order you'll be fine. OpenMP should make sure a whole line is printed at a time.

However, you will need to declare start and end as private in the pragma otherwise the threads will overwrite them and mess up your timings.



来源:https://stackoverflow.com/questions/3577144/openmp-and-file-i-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!