Statistiques
| Révision :

root / ETSN / MySteps.py @ 280

Historique | Voir | Annoter | Télécharger (957 octet)

1
#!/usr/bin/env python3
2

    
3
import numpy as np
4
import pyopencl as cl
5

    
6
a_np = np.random.rand(50000).astype(np.float32)
7
b_np = np.random.rand(50000).astype(np.float32)
8

    
9
ctx = cl.create_some_context()
10
queue = cl.CommandQueue(ctx)
11

    
12
mf = cl.mem_flags
13
a_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)
14
b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)
15

    
16
prg = cl.Program(ctx, """
17
__kernel void sum(
18
    __global const float *a_g, __global const float *b_g, __global float *res_g)
19
{
20
  int gid = get_global_id(0);
21
  res_g[gid] = a_g[gid] + b_g[gid];
22
}
23
""").build()
24

    
25
res_g = cl.Buffer(ctx, mf.WRITE_ONLY, a_np.nbytes)
26
knl = prg.sum  # Use this Kernel object for repeated calls
27
knl(queue, a_np.shape, None, a_g, b_g, res_g)
28

    
29
res_np = np.empty_like(a_np)
30
cl.enqueue_copy(queue, res_np, res_g)
31

    
32
# Check on CPU with Numpy:
33
print(res_np - (a_np + b_np))
34
print(np.linalg.norm(res_np - (a_np + b_np)))
35
assert np.allclose(res_np, a_np + b_np)