OpenMP and File I/O

2019-07-20 05:40发布

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?

2条回答
在下西门庆
2楼-- · 2019-07-20 06:09

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.

查看更多
We Are One
3楼-- · 2019-07-20 06:19

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.

查看更多
登录 后发表回答