|
| 1 | +/* |
| 2 | +Sample usage: |
| 3 | +
|
| 4 | + echo '1 2 3' | tr ' ' '\n' >vec_io.vec |
| 5 | + ./prog vec_io.cl vec_io.vec |
| 6 | +
|
| 7 | +Or you can use the default kernel and stdin input: |
| 8 | +
|
| 9 | + echo '1 2 3' | tr ' ' '\n' | ./prog |
| 10 | +
|
| 11 | +Generic boilerplate that: |
| 12 | +
|
| 13 | +- takes a vector as input either from stdin or from a file, one per line |
| 14 | +
|
| 15 | +- processes it with a kernel read from a file, one vector item per work item |
| 16 | +
|
| 17 | +- produces as output a vector of the same size to stdout |
| 18 | +
|
| 19 | +This allows you to quickly play with different kernels without recompiling the C code. |
| 20 | +
|
| 21 | +But is unsuitable for real applications, which require querying the CL implementation |
| 22 | +for limits, specially work group and memory maximum sizes. |
| 23 | +*/ |
| 24 | + |
| 25 | +#include "common.h" |
| 26 | + |
| 27 | +int main(int argc, char **argv) { |
| 28 | + char *cl_source_path; |
| 29 | + cl_float *io; |
| 30 | + cl_mem buffer; |
| 31 | + Common common; |
| 32 | + FILE *input_vector_file; |
| 33 | + float f; |
| 34 | + size_t i, n, nmax, io_sizeof; |
| 35 | + |
| 36 | + /* Treat CLI arguments. */ |
| 37 | + if (argc > 1) { |
| 38 | + cl_source_path = argv[1]; |
| 39 | + } else { |
| 40 | + cl_source_path = "vec_io.cl"; |
| 41 | + } |
| 42 | + if (argc > 2) { |
| 43 | + input_vector_file = fopen(argv[2], "r"); |
| 44 | + } else { |
| 45 | + input_vector_file = stdin; |
| 46 | + } |
| 47 | + |
| 48 | + /* Initialize data. */ |
| 49 | + n = 0; |
| 50 | + nmax = n + 1; |
| 51 | + io = malloc(nmax * sizeof(*io)); |
| 52 | + while(fscanf(input_vector_file, "%f", &f) != EOF) { |
| 53 | + io[n] = f; |
| 54 | + n++; |
| 55 | + if (n == nmax) { |
| 56 | + nmax *= 2; |
| 57 | + io = realloc(io, nmax * sizeof(*io)); |
| 58 | + } |
| 59 | + } |
| 60 | + io_sizeof = n * sizeof(*io); |
| 61 | + |
| 62 | + /* Run kernel. */ |
| 63 | + common_init_file(&common, cl_source_path); |
| 64 | + buffer = clCreateBuffer(common.context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, io_sizeof, io, NULL); |
| 65 | + clSetKernelArg(common.kernel, 0, sizeof(buffer), &buffer); |
| 66 | + clEnqueueNDRangeKernel(common.command_queue, common.kernel, 1, NULL, &n, NULL, 0, NULL, NULL); |
| 67 | + clFlush(common.command_queue); |
| 68 | + clFinish(common.command_queue); |
| 69 | + clEnqueueReadBuffer(common.command_queue, buffer, CL_TRUE, 0, io_sizeof, io, 0, NULL, NULL); |
| 70 | + |
| 71 | + /* Print result. */ |
| 72 | + for (i = 0; i < n; ++i) { |
| 73 | + printf("%f\n", io[i]); |
| 74 | + } |
| 75 | + |
| 76 | + /* Cleanup. */ |
| 77 | + clReleaseMemObject(buffer); |
| 78 | + common_deinit(&common); |
| 79 | + free(io); |
| 80 | + fclose(input_vector_file); |
| 81 | + return EXIT_SUCCESS; |
| 82 | +} |
0 commit comments