ssloy / tinyraytracer

A brief computer graphics / rendering course
https://github.com/ssloy/tinyraytracer/wiki
5k stars 333 forks source link

Multithreading for performance #33

Closed Qazalbash closed 1 year ago

Qazalbash commented 1 year ago

I added the multi-threading for performance. Here is the code for it

Code

// include this header file
#include <execution>

// All the code

// main function
int main(void) {
        // All the constants

        // put this code in place of the usual for loop
        // or you can use conditional inclusion (#if)

        std::vector<int> pixels(width * height); // vector to iterate over pixel indexes
        for (int i = 0; i < width * height; i++) pixels[i] = i; // assigning the values

        // multi-threaded for loop
        std::for_each(std::execution::par, pixels.begin(), pixels.end(), [&](int pix) {
                float dir_x      = (pix % width + 0.5) - width / 2.;
                float dir_y      = -(pix / width + 0.5) + height / 2.;
                float dir_z      = -height / (2. * tan(fov / 2.));
                framebuffer[pix] = cast_ray(vec3{0, 0, 0}, vec3{dir_x, dir_y, dir_z}.normalized());
        });

        // save the file

        return 0;
}

Test & Results

I tested this on Intel Core i7-1065G7 4 cores (8 threads) and got the performance of almost 2x. It was tested for 1024x1024 dimension. The results are,

Without multi-threading

gradf@virus:/media/gradf/Personal/tinyraytracer/build$ time ./tinyraytracer 

real    0m0.517s
user    0m0.491s
sys     0m0.009s

With multi-threading

gradf@virus:/media/gradf/Personal/tinyraytracer/build$ time ./tinyraytracer 

real    0m0.228s
user    0m0.973s
sys     0m0.018s
ssloy commented 1 year ago

Why not use openmp as done in my code?

ssloy commented 1 year ago

https://github.com/ssloy/tinyraytracer/blob/ce6b7852b7de11d485c017e16a9b990b94a66322/tinyraytracer.cpp#L132

Qazalbash commented 1 year ago

I am great full for your positive response. I was unaware of openmp. I have also tried to implement your code in C language, please check it and share your thoughts over it. I would be very happy for it. Click here.