Skip to main content

bevy_time/
stopwatch.rs

1#[cfg(feature = "bevy_reflect")]
2use bevy_reflect::{prelude::*, Reflect};
3use core::time::Duration;
4
5/// A Stopwatch is a struct that tracks elapsed time when started.
6///
7/// Note that in order to advance the stopwatch [`tick`](Stopwatch::tick) **MUST** be called.
8/// # Examples
9///
10/// ```
11/// # use bevy_time::*;
12/// use std::time::Duration;
13/// let mut stopwatch = Stopwatch::new();
14/// assert_eq!(stopwatch.elapsed_secs(), 0.0);
15///
16/// stopwatch.tick(Duration::from_secs_f32(1.0)); // tick one second
17/// assert_eq!(stopwatch.elapsed_secs(), 1.0);
18///
19/// stopwatch.pause();
20/// stopwatch.tick(Duration::from_secs_f32(1.0)); // paused stopwatches don't tick
21/// assert_eq!(stopwatch.elapsed_secs(), 1.0);
22///
23/// stopwatch.reset(); // reset the stopwatch
24/// assert!(stopwatch.is_paused());
25/// assert_eq!(stopwatch.elapsed_secs(), 0.0);
26/// ```
27#[derive(#[automatically_derived]impl ::core::clone::Clone for Stopwatch {
    #[inline]
    fn clone(&self) -> Self {
        Stopwatch {
            elapsed: ::core::clone::Clone::clone(&self.elapsed),
            is_paused: ::core::clone::Clone::clone(&self.is_paused),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Stopwatch {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Stopwatch",
            "elapsed", &self.elapsed, "is_paused", &&self.is_paused)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for Stopwatch {
    #[inline]
    fn default() -> Self {
        Stopwatch {
            elapsed: ::core::default::Default::default(),
            is_paused: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Stopwatch
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Stopwatch {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.is_paused == other.is_paused && self.elapsed == other.elapsed
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Stopwatch {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Duration>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
28#[cfg_attr(feature = "serialize", derive(#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
    {
        #[allow(unused_extern_crates, clippy :: useless_attribute)]
        extern crate serde as _serde;
        ;
        #[automatically_derived]
        impl<'de> _serde::Deserialize<'de> for Stopwatch {
            fn deserialize<__D>(__deserializer: __D)
                -> _serde::__private229::Result<Self, __D::Error> where
                __D: _serde::Deserializer<'de> {
                #[allow(non_camel_case_types)]
                #[doc(hidden)]
                enum __Field { __field0, __field1, __ignore, }
                #[doc(hidden)]
                struct __FieldVisitor;
                #[automatically_derived]
                impl<'de> _serde::de::Visitor<'de> for __FieldVisitor {
                    type Value = __Field;
                    fn expecting(&self,
                        __formatter: &mut _serde::__private229::Formatter)
                        -> _serde::__private229::fmt::Result {
                        _serde::__private229::Formatter::write_str(__formatter,
                            "field identifier")
                    }
                    fn visit_u64<__E>(self, __value: u64)
                        -> _serde::__private229::Result<Self::Value, __E> where
                        __E: _serde::de::Error {
                        match __value {
                            0u64 => _serde::__private229::Ok(__Field::__field0),
                            1u64 => _serde::__private229::Ok(__Field::__field1),
                            _ => _serde::__private229::Ok(__Field::__ignore),
                        }
                    }
                    fn visit_str<__E>(self, __value: &str)
                        -> _serde::__private229::Result<Self::Value, __E> where
                        __E: _serde::de::Error {
                        match __value {
                            "elapsed" => _serde::__private229::Ok(__Field::__field0),
                            "is_paused" => _serde::__private229::Ok(__Field::__field1),
                            _ => { _serde::__private229::Ok(__Field::__ignore) }
                        }
                    }
                    fn visit_bytes<__E>(self, __value: &[u8])
                        -> _serde::__private229::Result<Self::Value, __E> where
                        __E: _serde::de::Error {
                        match __value {
                            b"elapsed" => _serde::__private229::Ok(__Field::__field0),
                            b"is_paused" => _serde::__private229::Ok(__Field::__field1),
                            _ => { _serde::__private229::Ok(__Field::__ignore) }
                        }
                    }
                }
                #[automatically_derived]
                impl<'de> _serde::Deserialize<'de> for __Field {
                    #[inline]
                    fn deserialize<__D>(__deserializer: __D)
                        -> _serde::__private229::Result<Self, __D::Error> where
                        __D: _serde::Deserializer<'de> {
                        _serde::Deserializer::deserialize_identifier(__deserializer,
                            __FieldVisitor)
                    }
                }
                #[doc(hidden)]
                struct __Visitor<'de> {
                    marker: _serde::__private229::PhantomData<Stopwatch>,
                    lifetime: _serde::__private229::PhantomData<&'de ()>,
                }
                #[automatically_derived]
                impl<'de> _serde::de::Visitor<'de> for __Visitor<'de> {
                    type Value = Stopwatch;
                    fn expecting(&self,
                        __formatter: &mut _serde::__private229::Formatter)
                        -> _serde::__private229::fmt::Result {
                        _serde::__private229::Formatter::write_str(__formatter,
                            "struct Stopwatch")
                    }
                    #[inline]
                    fn visit_seq<__A>(self, mut __seq: __A)
                        -> _serde::__private229::Result<Self::Value, __A::Error>
                        where __A: _serde::de::SeqAccess<'de> {
                        let __field0 =
                            match _serde::de::SeqAccess::next_element::<Duration>(&mut __seq)?
                                {
                                _serde::__private229::Some(__value) => __value,
                                _serde::__private229::None =>
                                    return _serde::__private229::Err(_serde::de::Error::invalid_length(0usize,
                                                &"struct Stopwatch with 2 elements")),
                            };
                        let __field1 =
                            match _serde::de::SeqAccess::next_element::<bool>(&mut __seq)?
                                {
                                _serde::__private229::Some(__value) => __value,
                                _serde::__private229::None =>
                                    return _serde::__private229::Err(_serde::de::Error::invalid_length(1usize,
                                                &"struct Stopwatch with 2 elements")),
                            };
                        _serde::__private229::Ok(Stopwatch {
                                elapsed: __field0,
                                is_paused: __field1,
                            })
                    }
                    #[inline]
                    fn visit_map<__A>(self, mut __map: __A)
                        -> _serde::__private229::Result<Self::Value, __A::Error>
                        where __A: _serde::de::MapAccess<'de> {
                        let mut __field0: _serde::__private229::Option<Duration> =
                            _serde::__private229::None;
                        let mut __field1: _serde::__private229::Option<bool> =
                            _serde::__private229::None;
                        while let _serde::__private229::Some(__key) =
                                _serde::de::MapAccess::next_key::<__Field>(&mut __map)? {
                            match __key {
                                __Field::__field0 => {
                                    if _serde::__private229::Option::is_some(&__field0) {
                                        return _serde::__private229::Err(<__A::Error as
                                                        _serde::de::Error>::duplicate_field("elapsed"));
                                    }
                                    __field0 =
                                        _serde::__private229::Some(_serde::de::MapAccess::next_value::<Duration>(&mut __map)?);
                                }
                                __Field::__field1 => {
                                    if _serde::__private229::Option::is_some(&__field1) {
                                        return _serde::__private229::Err(<__A::Error as
                                                        _serde::de::Error>::duplicate_field("is_paused"));
                                    }
                                    __field1 =
                                        _serde::__private229::Some(_serde::de::MapAccess::next_value::<bool>(&mut __map)?);
                                }
                                _ => {
                                    let _ =
                                        _serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)?;
                                }
                            }
                        }
                        let __field0 =
                            match __field0 {
                                _serde::__private229::Some(__field0) => __field0,
                                _serde::__private229::None =>
                                    _serde::__private229::de::missing_field("elapsed")?,
                            };
                        let __field1 =
                            match __field1 {
                                _serde::__private229::Some(__field1) => __field1,
                                _serde::__private229::None =>
                                    _serde::__private229::de::missing_field("is_paused")?,
                            };
                        _serde::__private229::Ok(Stopwatch {
                                elapsed: __field0,
                                is_paused: __field1,
                            })
                    }
                }
                #[doc(hidden)]
                const FIELDS: &'static [&'static str] =
                    &["elapsed", "is_paused"];
                _serde::Deserializer::deserialize_struct(__deserializer,
                    "Stopwatch", FIELDS,
                    __Visitor {
                        marker: _serde::__private229::PhantomData::<Stopwatch>,
                        lifetime: _serde::__private229::PhantomData,
                    })
            }
        }
    };serde::Deserialize, #[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
    {
        #[allow(unused_extern_crates, clippy :: useless_attribute)]
        extern crate serde as _serde;
        ;
        #[automatically_derived]
        impl _serde::Serialize for Stopwatch {
            fn serialize<__S>(&self, __serializer: __S)
                -> _serde::__private229::Result<__S::Ok, __S::Error> where
                __S: _serde::Serializer {
                let mut __serde_state =
                    _serde::Serializer::serialize_struct(__serializer,
                            "Stopwatch", false as usize + 1 + 1)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "elapsed", &self.elapsed)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "is_paused", &self.is_paused)?;
                _serde::ser::SerializeStruct::end(__serde_state)
            }
        }
    };serde::Serialize))]
29#[cfg_attr(
30    feature = "bevy_reflect",
31    derive(const _: () =
    {
        impl bevy_reflect::GetTypeRegistration for Stopwatch where  {
            fn get_type_registration() -> bevy_reflect::TypeRegistration {
                let mut registration =
                    bevy_reflect::TypeRegistration::of::<Self>();
                registration.insert(<bevy_reflect::ReflectFromPtr as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.insert(<bevy_reflect::ReflectFromReflect as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.register_type_data_with::<ReflectDefault, Self,
                    _>(());
                registration
            }
            #[inline(never)]
            fn register_type_dependencies(registry:
                    &mut bevy_reflect::TypeRegistry) {
                <Duration as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
                <bool as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
            }
        }
        impl bevy_reflect::Typed for Stopwatch where  {
            #[inline(never)]
            fn type_info() -> &'static bevy_reflect::TypeInfo {
                static CELL: bevy_reflect::utility::NonGenericTypeInfoCell =
                    bevy_reflect::utility::NonGenericTypeInfoCell::new();
                CELL.get_or_set(#[inline(never)] ||
                        {
                            bevy_reflect::TypeInfo::Struct(bevy_reflect::structs::StructInfo::new::<Self>(&[bevy_reflect::NamedField::new::<Duration>("elapsed"),
                                                bevy_reflect::NamedField::new::<bool>("is_paused")]))
                        })
            }
        }
        #[allow(deprecated, reason =
        "derives on a deprecated type shouldn't be considered a usage")]
        impl bevy_reflect::TypePath for Stopwatch where  {
            fn type_path() -> &'static str {
                "bevy_time::stopwatch::Stopwatch"
            }
            fn short_type_path() -> &'static str { "Stopwatch" }
            fn type_ident() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("Stopwatch")
            }
            fn crate_name() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_time::stopwatch".split(':').next().unwrap())
            }
            fn module_path() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_time::stopwatch")
            }
        }
        impl bevy_reflect::Reflect for Stopwatch where  {
            #[inline]
            fn into_any(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn ::core::any::Any> {
                self
            }
            #[inline]
            fn as_any(&self) -> &dyn ::core::any::Any { self }
            #[inline]
            fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self }
            #[inline]
            fn into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect> {
                self
            }
            #[inline]
            fn as_reflect(&self) -> &dyn bevy_reflect::Reflect { self }
            #[inline]
            fn as_reflect_mut(&mut self) -> &mut dyn bevy_reflect::Reflect {
                self
            }
            #[inline]
            fn set(&mut self,
                value:
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>)
                ->
                    ::core::result::Result<(),
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>> {
                *self = <dyn bevy_reflect::Reflect>::take(value)?;
                ::core::result::Result::Ok(())
            }
        }
        impl bevy_reflect::structs::Struct for Stopwatch where  {
            fn field(&self, name: &str)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match name {
                    "elapsed" => ::core::option::Option::Some(&self.elapsed),
                    "is_paused" =>
                        ::core::option::Option::Some(&self.is_paused),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_mut(&mut self, name: &str)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match name {
                    "elapsed" =>
                        ::core::option::Option::Some(&mut self.elapsed),
                    "is_paused" =>
                        ::core::option::Option::Some(&mut self.is_paused),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_at(&self, index: usize)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&self.elapsed),
                    1usize => ::core::option::Option::Some(&self.is_paused),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_at_mut(&mut self, index: usize)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&mut self.elapsed),
                    1usize => ::core::option::Option::Some(&mut self.is_paused),
                    _ => ::core::option::Option::None,
                }
            }
            fn name_at(&self, index: usize) -> ::core::option::Option<&str> {
                match index {
                    0usize => ::core::option::Option::Some("elapsed"),
                    1usize => ::core::option::Option::Some("is_paused"),
                    _ => ::core::option::Option::None,
                }
            }
            fn index_of_name(&self, name: &str)
                -> ::core::option::Option<usize> {
                match name {
                    "elapsed" => ::core::option::Option::Some(0usize),
                    "is_paused" => ::core::option::Option::Some(1usize),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_len(&self) -> usize { 2usize }
            fn iter_fields(&self) -> bevy_reflect::structs::FieldIter {
                bevy_reflect::structs::FieldIter::new(self)
            }
            fn to_dynamic_struct(&self)
                ->
                    ::core::result::Result<bevy_reflect::structs::DynamicStruct,
                    bevy_reflect::ReflectCloneError> {
                let mut dynamic: bevy_reflect::structs::DynamicStruct =
                    ::core::default::Default::default();
                dynamic.set_represented_type(bevy_reflect::PartialReflect::get_represented_type_info(self));
                dynamic.insert_boxed("elapsed",
                    bevy_reflect::PartialReflect::to_dynamic(&self.elapsed)?);
                dynamic.insert_boxed("is_paused",
                    bevy_reflect::PartialReflect::to_dynamic(&self.is_paused)?);
                ::core::result::Result::Ok(dynamic)
            }
        }
        impl bevy_reflect::PartialReflect for Stopwatch where  {
            #[inline]
            fn get_represented_type_info(&self)
                -> ::core::option::Option<&'static bevy_reflect::TypeInfo> {
                ::core::option::Option::Some(<Self as
                            bevy_reflect::Typed>::type_info())
            }
            #[inline]
            fn try_apply(&mut self, value: &dyn bevy_reflect::PartialReflect)
                -> ::core::result::Result<(), bevy_reflect::ApplyError> {
                if let bevy_reflect::ReflectRef::Struct(struct_value) =
                        bevy_reflect::PartialReflect::reflect_ref(value) {
                    for (name, value) in
                        bevy_reflect::structs::Struct::iter_fields(struct_value) {
                        if let ::core::option::Option::Some(v) =
                                bevy_reflect::structs::Struct::field_mut(self, name) {
                            bevy_reflect::PartialReflect::try_apply(v, value)?;
                        }
                    }
                } else {
                    return ::core::result::Result::Err(bevy_reflect::ApplyError::MismatchedKinds {
                                from_kind: bevy_reflect::PartialReflect::reflect_kind(value),
                                to_kind: bevy_reflect::ReflectKind::Struct,
                            });
                }
                ::core::result::Result::Ok(())
            }
            #[inline]
            fn reflect_kind(&self) -> bevy_reflect::ReflectKind {
                bevy_reflect::ReflectKind::Struct
            }
            #[inline]
            fn reflect_ref(&self) -> bevy_reflect::ReflectRef {
                bevy_reflect::ReflectRef::Struct(self)
            }
            #[inline]
            fn reflect_mut(&mut self) -> bevy_reflect::ReflectMut {
                bevy_reflect::ReflectMut::Struct(self)
            }
            #[inline]
            fn reflect_owned(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                -> bevy_reflect::ReflectOwned {
                bevy_reflect::ReflectOwned::Struct(self)
            }
            #[inline]
            fn try_into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect>> {
                ::core::result::Result::Ok(self)
            }
            #[inline]
            fn try_as_reflect(&self)
                -> ::core::option::Option<&dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn try_as_reflect_mut(&mut self)
                -> ::core::option::Option<&mut dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn into_partial_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect> {
                self
            }
            #[inline]
            fn as_partial_reflect(&self)
                -> &dyn bevy_reflect::PartialReflect {
                self
            }
            #[inline]
            fn as_partial_reflect_mut(&mut self)
                -> &mut dyn bevy_reflect::PartialReflect {
                self
            }
            fn reflect_partial_eq(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<bool> {
                let value =
                    <dyn bevy_reflect::PartialReflect>::try_downcast_ref::<Self>(value);
                if let ::core::option::Option::Some(value) = value {
                    ::core::option::Option::Some(::core::cmp::PartialEq::eq(self,
                            value))
                } else { ::core::option::Option::Some(false) }
            }
            fn reflect_partial_cmp(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<::core::cmp::Ordering> {
                (bevy_reflect::structs::struct_partial_cmp)(self, value)
            }
            #[inline]
            fn reflect_clone(&self)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::ReflectCloneError> {
                ::core::result::Result::Ok(bevy_reflect::__macro_exports::alloc_utils::Box::new(::core::clone::Clone::clone(self)))
            }
        }
        impl bevy_reflect::FromReflect for Stopwatch where  {
            fn from_reflect(reflect: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<Self> {
                if let bevy_reflect::ReflectRef::Struct(__ref_struct) =
                        bevy_reflect::PartialReflect::reflect_ref(reflect) {
                    let mut __this =
                        <Self as ::core::default::Default>::default();
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <Duration as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "elapsed")?))() {
                        __this.elapsed = __field;
                    }
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <bool as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::structs::Struct::field(__ref_struct,
                                                    "is_paused")?))() {
                        __this.is_paused = __field;
                    }
                    ::core::option::Option::Some(__this)
                } else { ::core::option::Option::None }
            }
        }
    };Reflect),
32    reflect(Default, Clone, PartialEq)
33)]
34pub struct Stopwatch {
35    elapsed: Duration,
36    is_paused: bool,
37}
38
39impl Stopwatch {
40    /// Create a new unpaused `Stopwatch` with no elapsed time.
41    ///
42    /// # Examples
43    /// ```
44    /// # use bevy_time::*;
45    /// let stopwatch = Stopwatch::new();
46    /// assert_eq!(stopwatch.elapsed_secs(), 0.0);
47    /// assert_eq!(stopwatch.is_paused(), false);
48    /// ```
49    pub fn new() -> Self {
50        Default::default()
51    }
52
53    /// Returns the elapsed time since the last [`reset`](Stopwatch::reset)
54    /// of the stopwatch.
55    ///
56    /// # Examples
57    /// ```
58    /// # use bevy_time::*;
59    /// use std::time::Duration;
60    /// let mut stopwatch = Stopwatch::new();
61    /// stopwatch.tick(Duration::from_secs(1));
62    /// assert_eq!(stopwatch.elapsed(), Duration::from_secs(1));
63    /// ```
64    ///
65    /// # See Also
66    ///
67    /// [`elapsed_secs`](Stopwatch::elapsed_secs) - if an `f32` value is desirable instead.
68    /// [`elapsed_secs_f64`](Stopwatch::elapsed_secs_f64) - if an `f64` is desirable instead.
69    #[inline]
70    pub fn elapsed(&self) -> Duration {
71        self.elapsed
72    }
73
74    /// Returns the elapsed time since the last [`reset`](Stopwatch::reset)
75    /// of the stopwatch, in seconds.
76    ///
77    /// # Examples
78    /// ```
79    /// # use bevy_time::*;
80    /// use std::time::Duration;
81    /// let mut stopwatch = Stopwatch::new();
82    /// stopwatch.tick(Duration::from_secs(1));
83    /// assert_eq!(stopwatch.elapsed_secs(), 1.0);
84    /// ```
85    ///
86    /// # See Also
87    ///
88    /// [`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead.
89    /// [`elapsed_secs_f64`](Stopwatch::elapsed_secs_f64) - if an `f64` is desirable instead.
90    #[inline]
91    pub fn elapsed_secs(&self) -> f32 {
92        self.elapsed().as_secs_f32()
93    }
94
95    /// Returns the elapsed time since the last [`reset`](Stopwatch::reset)
96    /// of the stopwatch, in seconds, as `f64`.
97    ///
98    /// # See Also
99    ///
100    /// [`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead.
101    /// [`elapsed_secs`](Stopwatch::elapsed_secs) - if an `f32` is desirable instead.
102    #[inline]
103    pub fn elapsed_secs_f64(&self) -> f64 {
104        self.elapsed().as_secs_f64()
105    }
106
107    /// Sets the elapsed time of the stopwatch.
108    ///
109    /// # Examples
110    /// ```
111    /// # use bevy_time::*;
112    /// use std::time::Duration;
113    /// let mut stopwatch = Stopwatch::new();
114    /// stopwatch.set_elapsed(Duration::from_secs_f32(1.0));
115    /// assert_eq!(stopwatch.elapsed_secs(), 1.0);
116    /// ```
117    #[inline]
118    pub fn set_elapsed(&mut self, time: Duration) {
119        self.elapsed = time;
120    }
121
122    /// Advance the stopwatch by `delta` seconds.
123    /// If the stopwatch is paused, ticking will not have any effect
124    /// on elapsed time.
125    ///
126    /// # Examples
127    /// ```
128    /// # use bevy_time::*;
129    /// use std::time::Duration;
130    /// let mut stopwatch = Stopwatch::new();
131    /// stopwatch.tick(Duration::from_secs_f32(1.5));
132    /// assert_eq!(stopwatch.elapsed_secs(), 1.5);
133    /// ```
134    pub fn tick(&mut self, delta: Duration) -> &Self {
135        if !self.is_paused() {
136            self.elapsed = self.elapsed.saturating_add(delta);
137        }
138        self
139    }
140
141    /// Pauses the stopwatch. Any call to [`tick`](Stopwatch::tick) while
142    /// paused will not have any effect on the elapsed time.
143    ///
144    /// # Examples
145    /// ```
146    /// # use bevy_time::*;
147    /// use std::time::Duration;
148    /// let mut stopwatch = Stopwatch::new();
149    /// stopwatch.pause();
150    /// stopwatch.tick(Duration::from_secs_f32(1.5));
151    /// assert!(stopwatch.is_paused());
152    /// assert_eq!(stopwatch.elapsed_secs(), 0.0);
153    /// ```
154    #[inline]
155    pub fn pause(&mut self) {
156        self.is_paused = true;
157    }
158
159    /// Unpauses the stopwatch. Resume the effect of ticking on elapsed time.
160    ///
161    /// # Examples
162    /// ```
163    /// # use bevy_time::*;
164    /// use std::time::Duration;
165    /// let mut stopwatch = Stopwatch::new();
166    /// stopwatch.pause();
167    /// stopwatch.tick(Duration::from_secs_f32(1.0));
168    /// stopwatch.unpause();
169    /// stopwatch.tick(Duration::from_secs_f32(1.0));
170    /// assert!(!stopwatch.is_paused());
171    /// assert_eq!(stopwatch.elapsed_secs(), 1.0);
172    /// ```
173    #[inline]
174    pub fn unpause(&mut self) {
175        self.is_paused = false;
176    }
177
178    /// Returns `true` if the stopwatch is paused.
179    ///
180    /// # Examples
181    /// ```
182    /// # use bevy_time::*;
183    /// let mut stopwatch = Stopwatch::new();
184    /// assert!(!stopwatch.is_paused());
185    /// stopwatch.pause();
186    /// assert!(stopwatch.is_paused());
187    /// stopwatch.unpause();
188    /// assert!(!stopwatch.is_paused());
189    /// ```
190    #[inline]
191    pub fn is_paused(&self) -> bool {
192        self.is_paused
193    }
194
195    /// Resets the stopwatch. The reset doesn't affect the paused state of the stopwatch.
196    ///
197    /// # Examples
198    /// ```
199    /// # use bevy_time::*;
200    /// use std::time::Duration;
201    /// let mut stopwatch = Stopwatch::new();
202    /// stopwatch.tick(Duration::from_secs_f32(1.5));
203    /// stopwatch.reset();
204    /// assert_eq!(stopwatch.elapsed_secs(), 0.0);
205    /// ```
206    #[inline]
207    pub fn reset(&mut self) {
208        self.elapsed = Default::default();
209    }
210}