1 /* This sample demonstrates the way you can perform independed tasks
2 on the different GPUs */
4 // Disable some warnings which are caused with CUDA headers
6 #pragma warning(disable: 4201 4408 4100)
11 #include "opencv2/core/core.hpp"
12 #include "opencv2/cudaarithm.hpp"
15 # include "tbb/tbb_stddef.h"
16 # if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202
18 # include "tbb/task.h"
26 #if !defined(HAVE_CUDA) || !defined(HAVE_TBB) || defined(__arm__)
30 #if !defined(HAVE_CUDA)
31 std::cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n";
34 #if !defined(HAVE_TBB)
35 std::cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n";
39 std::cout << "Unsupported for ARM CUDA library." << std::endl;
48 #include <cuda_runtime.h>
52 using namespace cv::cuda;
54 struct Worker { void operator()(int device_id) const; };
55 void destroyContexts();
57 #define safeCall(expr) safeCall_(expr, #expr, __FILE__, __LINE__)
58 inline void safeCall_(int code, const char* expr, const char* file, int line)
60 if (code != CUDA_SUCCESS)
62 std::cout << "CUDA driver API error: code " << code << ", expr " << expr
63 << ", file " << file << ", line " << line << endl;
69 // Each GPU is associated with its own context
70 CUcontext contexts[2];
74 int num_devices = getCudaEnabledDeviceCount();
77 std::cout << "Two or more GPUs are required\n";
81 for (int i = 0; i < num_devices; ++i)
83 cv::cuda::printShortCudaDeviceInfo(i);
85 DeviceInfo dev_info(i);
86 if (!dev_info.isCompatible())
88 std::cout << "CUDA module isn't built for GPU #" << i << " ("
89 << dev_info.name() << ", CC " << dev_info.majorVersion()
90 << dev_info.minorVersion() << "\n";
95 // Init CUDA Driver API
98 // Create context for GPU #0
100 safeCall(cuDeviceGet(&device, 0));
101 safeCall(cuCtxCreate(&contexts[0], 0, device));
103 CUcontext prev_context;
104 safeCall(cuCtxPopCurrent(&prev_context));
106 // Create context for GPU #1
107 safeCall(cuDeviceGet(&device, 1));
108 safeCall(cuCtxCreate(&contexts[1], 0, device));
110 safeCall(cuCtxPopCurrent(&prev_context));
112 // Execute calculation in two threads using two GPUs
113 int devices[] = {0, 1};
114 tbb::parallel_do(devices, devices + 2, Worker());
121 void Worker::operator()(int device_id) const
123 // Set the proper context
124 safeCall(cuCtxPushCurrent(contexts[device_id]));
126 Mat src(1000, 1000, CV_32F);
130 rng.fill(src, RNG::UNIFORM, 0, 1);
133 cv::transpose(src, dst);
138 cuda::transpose(d_src, d_dst);
141 bool passed = cv::norm(dst - Mat(d_dst), NORM_INF) < 1e-3;
142 std::cout << "GPU #" << device_id << " (" << DeviceInfo().name() << "): "
143 << (passed ? "passed" : "FAILED") << endl;
145 // Deallocate data here, otherwise deallocation will be performed
146 // after context is extracted from the stack
150 CUcontext prev_context;
151 safeCall(cuCtxPopCurrent(&prev_context));
155 void destroyContexts()
157 safeCall(cuCtxDestroy(contexts[0]));
158 safeCall(cuCtxDestroy(contexts[1]));