Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add thrust algorithms #2

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions 005_thrust_algos/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
all: hw

hw:
nvcc -x cu -O3 -std=c++20 --extended-lambda -arch=sm_86 -I/usr/local/cuda-12.2/bin/../include ./algos.cu -o main -L/usr/local/cuda-12.2/bin/../lib64

clean:
rm -f main

.PHONY: clean hw
91 changes: 91 additions & 0 deletions 005_thrust_algos/algos.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#include <thrust/sort.h>
#include <thrust/device_vector.h>

struct plus_one_functor {
__device__
int operator()(int x) {
return x + 1;
}
};

void print_vector(thrust::device_vector<int> v) {
thrust::for_each(v.begin(), v.end(), [] __host__ __device__(int val) {
printf("%d ", val);
});
std::cout << std::endl;
}

int main() {
// Sorting
{
std::vector<int> h_vec{3, 1, 4, 2, 8, 5, 9, 12, 6};
thrust::device_vector<int> d_vec = h_vec;
thrust::sort(
thrust::device,
d_vec.begin(),
d_vec.end()
);
print_vector(d_vec);
}

// Filling
{
thrust::device_vector<int> d_vec(10);
thrust::fill(
thrust::device,
d_vec.begin(),
d_vec.end(),
101
);
print_vector(d_vec);
}

// Sequence
{
thrust::device_vector<int> d_vec(10);
thrust::sequence(
thrust::device,
d_vec.begin(),
d_vec.end()
);
print_vector(d_vec);
}

// Transform
{
thrust::device_vector<int> d_vec(10);
thrust::sequence(
thrust::device,
d_vec.begin(),
d_vec.end()
);
print_vector(d_vec);
// Now, we will add 1 to every element
thrust::transform(
thrust::device,
d_vec.begin(),
d_vec.end(),
d_vec.begin(),
plus_one_functor()
);
print_vector(d_vec);
}

// Merge
{
std::vector<int> h_vec1 = {1, 2, 3, 4, 5};
std::vector<int> h_vec2 = {6, 7, 8, 9, 10};
thrust::device_vector<int> d_vec1 = h_vec1;
thrust::device_vector<int> d_vec2 = h_vec2;
thrust::device_vector<int> merged_vec(10);
thrust::merge(
thrust::device,
d_vec1.begin(),
d_vec1.end(),
d_vec2.begin(),
d_vec2.end(),
merged_vec.begin()
);
print_vector(merged_vec);
}
}