"""Example 9 — Streams (command queues) and events.

The commands of one stream run in order; two streams can run in parallel.
Events serve to time the GPU without measuring the host's time.

Concepts: stream (CUDA) = command queue (OpenCL, Metal), events,
asynchronous launches, ``kernel[grid, block, stream]``.

    python examples/09_streams_events.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu


@gpu.jit
def scale(a, factor):
    i = gpu.grid(1)
    if i < a.size:
        a[i] = a[i] * factor


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(1 << 20, 4096)
    chunks = [np.full(n, k, np.float32) for k in range(4)]
    streams = [gpu.stream() for _ in chunks]

    start, end = gpu.event(), gpu.event()
    start.record()
    results = []
    for chunk, s in zip(chunks, streams):
        d = gpu.to_device(chunk, stream=s)                     # copy on stream s
        scale[(n + 255) // 256, 256, s](d, np.float32(2))      # kernel on stream s
        results.append(d)
    for s in streams:
        s.synchronize()
    end.record()
    end.synchronize()

    for k, d in enumerate(results):
        assert (d.copy_to_host() == 2 * k).all()
    print(f"4 streams processed in {start.elapsed_time(end):.2f} ms (measured with events)")

    with streams[0].auto_synchronize():                    # synchronization when leaving the block
        scale[(n + 255) // 256, 256, streams[0]](results[0], np.float32(0.5))
    print("auto_synchronize: OK")


if __name__ == "__main__":
    main()
