Skip to content

Commit 8f3dc16

Browse files
committed
update original
1 parent d8828f5 commit 8f3dc16

6 files changed

Lines changed: 118 additions & 0 deletions

File tree

rust-cookbook/ci/dictionary.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@ symphonia
365365
syslog
366366
SyslogError
367367
SystemRandom
368+
systemtime
368369
SystemTime
369370
SystemTimeError
370371
tcpip

rust-cookbook/src/datetime.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
| Recipe | Crates | Categories |
44
|--------|--------|------------|
55
| [Measure elapsed time][ex-measure-elapsed-time] | [![std-badge]][std] | [![cat-time-badge]][cat-time] |
6+
| [Deadline arithmetic with Duration][ex-deadline-arithmetic-std] | [![std-badge]][std] | [![cat-time-badge]][cat-time] |
7+
| [Convert SystemTime to UNIX timestamp][ex-convert-to-unix-timestamp-std] | [![std-badge]][std] | [![cat-time-badge]][cat-time] |
8+
| [Benchmark a closure with Instant][ex-benchmark-closure] | [![std-badge]][std] | [![cat-time-badge]][cat-time] |
69
| [Perform checked date and time calculations][ex-datetime-arithmetic] | [![chrono-badge]][chrono] | [![cat-date-and-time-badge]][cat-date-and-time] |
710
| [Convert a local time to another timezone][ex-convert-datetime-timezone] | [![chrono-badge]][chrono] | [![cat-date-and-time-badge]][cat-date-and-time] |
811
| [Examine the date and time][ex-examine-date-and-time] | [![chrono-badge]][chrono] | [![cat-date-and-time-badge]][cat-date-and-time] |
@@ -11,6 +14,9 @@
1114
| [Parse string into DateTime struct][ex-parse-datetime] | [![chrono-badge]][chrono] | [![cat-date-and-time-badge]][cat-date-and-time] |
1215

1316
[ex-measure-elapsed-time]: datetime/duration.html#measure-the-elapsed-time-between-two-code-sections
17+
[ex-deadline-arithmetic-std]: datetime/duration.html#deadline-arithmetic-with-instant
18+
[ex-convert-to-unix-timestamp-std]: datetime/duration.html#convert-systemtime-to-unix-timestamp
19+
[ex-benchmark-closure]: datetime/duration.html#benchmark-a-closure-with-instant
1420
[ex-datetime-arithmetic]: datetime/duration.html#perform-checked-date-and-time-calculations
1521
[ex-convert-datetime-timezone]: datetime/duration.html#convert-a-local-time-to-another-timezone
1622
[ex-examine-date-and-time]: datetime/parse.html#examine-the-date-and-time

rust-cookbook/src/datetime/duration.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
{{#include duration/profile.md}}
44

5+
{{#include duration/deadline.md}}
6+
7+
{{#include duration/convert_to_unix.md}}
8+
9+
{{#include duration/benchmark.md}}
10+
511
{{#include duration/checked.md}}
612

713
{{#include duration/timezone.md}}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## Benchmark a closure with `Instant`
2+
3+
[![std-badge]][std] [![cat-time-badge]][cat-time]
4+
5+
Initializes a `weights` vector, calculates half of its total sum into `half_load`,
6+
and uses `benchmark` to measure the performance of `subset_sum` which takes a slice of weights and a target value and finds a subset whose weights sum to the target.
7+
8+
`benchmark` measures the average time required to call a closure a specified number of times using [`Instant::now`] and [`Instant::elapsed`].
9+
It uses [`black_box`] to prevent the compiler from optimizing away the closure's computation since its return value is ignored.
10+
11+
```rust,edition2021
12+
use std::time::{Duration, Instant};
13+
14+
fn subset_sum(weights: &[u64], target: u64) -> Option<u32> {
15+
for mask in 0..1u32 << weights.len() {
16+
let sum: u64 = weights
17+
.iter()
18+
.enumerate()
19+
.filter(|(i, _)| mask >> i & 1 == 1)
20+
.map(|(_, weight)| weight)
21+
.sum();
22+
23+
if sum == target {
24+
return Some(mask);
25+
}
26+
}
27+
None
28+
}
29+
30+
fn benchmark<F, T>(runs: u32, mut f: F) -> Duration
31+
where
32+
F: FnMut() -> T,
33+
{
34+
let start = Instant::now();
35+
36+
for _ in 0..runs {
37+
std::hint::black_box(f());
38+
}
39+
40+
start.elapsed() / runs
41+
}
42+
43+
fn main() {
44+
let weights: Vec<u64> = (1..=18).map(|kg| kg * 2).collect();
45+
let half_load = weights.iter().sum::<u64>() / 2;
46+
47+
for parcels in 12..=weights.len() {
48+
let mean = benchmark(3, || subset_sum(&weights[..parcels], half_load));
49+
println!("{:2} parcels: {:>10.2?}", parcels, mean);
50+
}
51+
}
52+
```
53+
54+
[`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now
55+
[`Instant::elapsed`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.elapsed
56+
[`black_box`]: https://doc.rust-lang.org/std/hint/fn.black_box.html
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
## Convert `SystemTime` to Unix timestamp
2+
3+
[![std-badge]][std] [![cat-time-badge]][cat-time]
4+
5+
Converts the current [`SystemTime`] to seconds since the Unix epoch, then computes the original time
6+
by adding the unix timestamp to [`SystemTime::UNIX_EPOCH`] constant.
7+
8+
```rust,edition2021
9+
use std::time::{SystemTime, SystemTimeError};
10+
11+
fn main() -> Result<(), SystemTimeError> {
12+
let now = SystemTime::now();
13+
let since_unix_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
14+
println!("Unix timestamp: {}", since_unix_epoch.as_secs());
15+
16+
let from_unix_timestamp = SystemTime::UNIX_EPOCH + since_unix_epoch;
17+
println!("Back to SystemTime: {:?}", from_unix_timestamp);
18+
19+
Ok(())
20+
}
21+
```
22+
[`SystemTime`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html
23+
[`SystemTime::UNIX_EPOCH`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#associatedconstant.UNIX_EPOCH
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
## Deadline arithmetic with `Instant`
2+
3+
[![std-badge]][std] [![cat-time-badge]][cat-time]
4+
5+
Calculates a one second [`Duration`]. Computes `deadline` one second from [`Instant::now`].
6+
Sleeps for one second and compares `deadline` with [`Instant::now`] to check if the deadline has passed.
7+
8+
```rust,edition2021
9+
# use std::thread;
10+
use std::time::{Duration, Instant};
11+
# fn sleep(duration: Duration) {
12+
# thread::sleep(duration);
13+
# }
14+
15+
fn main() {
16+
let one_second = Duration::from_secs(1);
17+
let deadline = Instant::now() + one_second;
18+
19+
sleep(Duration::from_secs(1));
20+
if Instant::now() > deadline {
21+
println!("Deadline has passed");
22+
}
23+
}
24+
```
25+
[`Duration`]: https://doc.rust-lang.org/std/time/struct.Duration.html
26+
[`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now

0 commit comments

Comments
 (0)