-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple.ts
More file actions
66 lines (54 loc) · 1.93 KB
/
Copy pathsimple.ts
File metadata and controls
66 lines (54 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as cl from '@node-3d/opencl';
const { context, device } = cl.quickStart(true);
const queue = cl.createCommandQueue(context, device);
const BUFFER_SIZE = 10;
const BYTE_SIZE = BUFFER_SIZE * Uint32Array.BYTES_PER_ELEMENT;
const arrayA = new Uint32Array(BUFFER_SIZE);
const arrayB = new Uint32Array(BUFFER_SIZE);
const arrayC = new Uint32Array(BUFFER_SIZE);
for (let i = 0; i < BUFFER_SIZE; i++) {
arrayA[i] = i;
arrayB[i] = i * 2;
}
// Create buffer for arrayA and arrayB and copy host contents
const bufferA = cl.createBuffer(context, cl.MEM_READ_ONLY, BYTE_SIZE);
const bufferB = cl.createBuffer(context, cl.MEM_READ_ONLY, BYTE_SIZE);
// Create buffer for arrayC to read results
const bufferC = cl.createBuffer(context, cl.MEM_WRITE_ONLY, BYTE_SIZE);
// Create a program object
const program = cl.createProgramWithSource(
context,
`
__kernel
void vadd(__global int *a, __global int *b, __global int *c, uint num) {
size_t i = get_global_id(0);
if (i < num) {
c[i] = a[i] + b[i];
}
}
`,
);
cl.buildProgram(program);
// Create a kernel object
const kernel = cl.createKernel(program, 'vadd');
// Set kernel args
cl.setKernelArg(kernel, 0, 'uint*', bufferA);
cl.setKernelArg(kernel, 1, 'uint*', bufferB);
cl.setKernelArg(kernel, 2, 'uint*', bufferC);
cl.setKernelArg(kernel, 3, 'uint', BUFFER_SIZE);
// Do the work
cl.enqueueWriteBuffer(queue, bufferA, true, 0, BYTE_SIZE, arrayA);
cl.enqueueWriteBuffer(queue, bufferB, true, 0, BYTE_SIZE, arrayB);
cl.enqueueNDRangeKernel(queue, kernel, 1, undefined, [BUFFER_SIZE]);
cl.enqueueReadBuffer(queue, bufferC, true, 0, BYTE_SIZE, arrayC);
// print results
console.log(`A = [${arrayA.join(', ')}]`);
console.log(`B = [${arrayB.join(', ')}]`);
console.log(`C = [${arrayC.join(', ')}]`);
// Cleanup - release each CL object
cl.releaseCommandQueue(queue);
cl.releaseKernel(kernel);
cl.releaseProgram(program);
cl.releaseMemObject(bufferA);
cl.releaseMemObject(bufferB);
cl.releaseMemObject(bufferC);