|
| 1 | +use crate::cuda_sys::cuda::{ |
| 2 | + cuEventCreate, cuEventDestroy_v2, cuEventElapsedTime, cuEventQuery, cuEventRecord, |
| 3 | + cuEventSynchronize, CUevent, |
| 4 | +}; |
| 5 | +use crate::error::{CudaResult, DropResult, ToResult}; |
| 6 | +use crate::stream::Stream; |
| 7 | + |
| 8 | +use std::mem; |
| 9 | +use std::ptr; |
| 10 | + |
| 11 | +bitflags! { |
| 12 | + pub struct EventFlags: u32 { |
| 13 | + const DEFAULT = 0x0; |
| 14 | + const BLOCKING_SYNC = 0x1; |
| 15 | + const DISABLE_TIMING = 0x2; |
| 16 | + const INTERPROCESS = 0x4; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +#[derive(Debug)] |
| 21 | +pub struct Event(CUevent); |
| 22 | + |
| 23 | +impl Event { |
| 24 | + pub fn new(flags: EventFlags) -> CudaResult<Self> { |
| 25 | + unsafe { |
| 26 | + let mut event: CUevent = mem::zeroed(); |
| 27 | + cuEventCreate(&mut event, flags.bits()).to_result()?; |
| 28 | + Ok(Event(event)) |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + pub fn record(&self, stream: Stream) -> CudaResult<&Self> { |
| 33 | + unsafe { |
| 34 | + cuEventRecord(self.0, stream.get_inner()).to_result()?; |
| 35 | + Ok(self) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + pub fn query(&self) -> CudaResult<&Self> { |
| 40 | + unsafe { |
| 41 | + cuEventQuery(self.0).to_result()?; |
| 42 | + Ok(self) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + pub fn synchronize(&self) -> CudaResult<&Self> { |
| 47 | + unsafe { |
| 48 | + cuEventSynchronize(self.0).to_result()?; |
| 49 | + Ok(self) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + pub fn elapsed_time(&self, start: &Self) -> CudaResult<f32> { |
| 54 | + unsafe { |
| 55 | + let mut millis: f32 = 0.0; |
| 56 | + cuEventElapsedTime(&mut millis, start.0, self.0).to_result()?; |
| 57 | + Ok(millis) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + pub fn drop(mut event: Event) -> DropResult<Event> { |
| 62 | + if event.0.is_null() { |
| 63 | + return Ok(()); |
| 64 | + } |
| 65 | + |
| 66 | + unsafe { |
| 67 | + let inner = mem::replace(&mut event.0, ptr::null_mut()); |
| 68 | + match cuEventDestroy_v2(inner).to_result() { |
| 69 | + Ok(()) => { |
| 70 | + mem::forget(event); |
| 71 | + Ok(()) |
| 72 | + } |
| 73 | + Err(e) => Err((e, Event(inner))), |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl Drop for Event { |
| 80 | + fn drop(&mut self) { |
| 81 | + unsafe { cuEventDestroy_v2(self.0) } |
| 82 | + .to_result() |
| 83 | + .expect("Failed to destroy CUDA event"); |
| 84 | + } |
| 85 | +} |
0 commit comments