This repository has been archived by the owner on Feb 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 221
/
csv_read_parallel.rs
86 lines (74 loc) · 2.51 KB
/
csv_read_parallel.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use crossbeam_channel::unbounded;
use std::sync::Arc;
use std::thread;
use std::time::SystemTime;
use arrow2::array::Array;
use arrow2::chunk::Chunk;
use arrow2::{error::Result, io::csv::read};
fn parallel_read(path: &str) -> Result<Vec<Chunk<Arc<dyn Array>>>> {
let batch_size = 100;
let has_header = true;
let projection = None;
// prepare a channel to send serialized records from threads
let (tx, rx) = unbounded();
let mut reader = read::ReaderBuilder::new().from_path(path)?;
let fields = read::infer_schema(&mut reader, Some(batch_size * 10), has_header, &read::infer)?;
let fields = Arc::new(fields);
let start = SystemTime::now();
// spawn a thread to produce `Vec<ByteRecords>` (IO bounded)
let child = thread::spawn(move || {
let mut line_number = 0;
let mut size = 1;
while size > 0 {
let mut rows = vec![read::ByteRecord::default(); batch_size];
let rows_read = read::read_rows(&mut reader, 0, &mut rows).unwrap();
rows.truncate(rows_read);
line_number += rows.len();
size = rows.len();
tx.send((rows, line_number)).unwrap();
}
});
let mut children = Vec::new();
// use 3 consumers of to decompress, decode and deserialize.
for _ in 0..3 {
let rx_consumer = rx.clone();
let consumer_fields = fields.clone();
let child = thread::spawn(move || {
let (rows, line_number) = rx_consumer.recv().unwrap();
let start = SystemTime::now();
println!("consumer start - {}", line_number);
let batch = read::deserialize_batch(
&rows,
&consumer_fields,
projection,
0,
read::deserialize_column,
)
.unwrap();
println!(
"consumer end - {:?}: {}",
start.elapsed().unwrap(),
line_number,
);
batch
});
children.push(child);
}
child.join().expect("child thread panicked");
let batches = children
.into_iter()
.map(|x| x.join().unwrap())
.collect::<Vec<_>>();
println!("Finished - {:?}", start.elapsed().unwrap());
Ok(batches)
}
fn main() -> Result<()> {
use std::env;
let args: Vec<String> = env::args().collect();
let file_path = &args[1];
let batches = parallel_read(file_path)?;
for batch in batches {
println!("{}", batch.len())
}
Ok(())
}