Last active
August 19, 2024 02:36
-
-
Save WhiteCat6142/1e1fda614801ed6ac054e327d81da5ba to your computer and use it in GitHub Desktop.
thrust.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <thrust/copy.h> | |
| #include <thrust/async/copy.h> | |
| #include <thrust/transform.h> | |
| #include <thrust/host_vector.h> | |
| #include <thrust/device_vector.h> | |
| #include <thrust/execution_policy.h> | |
| #include <cassert> | |
| #include <cmath> | |
| #include <iostream> | |
| //using namespace std; | |
| template <typename T> | |
| struct xxx : public thrust::unary_function<T,T> | |
| { | |
| __host__ __device__ | |
| T operator()(T d) const | |
| { | |
| return d * d; | |
| } | |
| }; | |
| thrust::device_event Double(thrust::host_vector<float>& ts) { | |
| std::size_t size = ts.size(); | |
| auto device_ts = thrust::device_vector<float>(size); | |
| auto result = thrust::device_vector<float>(size); | |
| thrust::device_event e(thrust::new_stream); | |
| cudaStream_t s1; | |
| cudaStreamCreate(&s1); | |
| auto copy_ts_event = thrust::copy( | |
| // thrust::device.on(s1), | |
| // thrust::host, | |
| // thrust::device, | |
| ts.begin(), | |
| ts.end(), | |
| device_ts.begin() | |
| ); | |
| //copy_ts_event.wait(); | |
| xxx<float> unary_op; | |
| auto double_ts_event = thrust::transform( | |
| thrust::device, | |
| device_ts.begin(), | |
| device_ts.end(), | |
| result.begin(), | |
| unary_op | |
| ); | |
| //thrust::device_event e1(thrust::new_stream); | |
| // デバイスからホストへの非同期コピー | |
| auto copy_back_ts_event = thrust::copy( | |
| // thrust::device.after(copy_ts_event), | |
| // thrust::device,//host | |
| // thrust::host, | |
| result.begin(), | |
| result.end(), | |
| ts.begin() | |
| ); | |
| return e; | |
| } | |
| thrust::device_event Double2(thrust::host_vector<float>& floats, thrust::host_vector<float>& floats2) { | |
| return thrust::when_all(Double(floats), Double(floats2)); | |
| } | |
| int main() { | |
| std::size_t size = 1024; | |
| auto floats = thrust::host_vector<float>(size); | |
| for (std::size_t i = 0; i < size; ++i) { | |
| floats[i]=i; | |
| } | |
| auto event = Double(floats); | |
| //event.wait(); | |
| for (std::size_t i = 0; i < size; ++i) { | |
| assert(std::abs(floats[i] - i * i) < 1e-5); | |
| } | |
| std::cout << "Success!" << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment