Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hanchang/ba4f7e0efec7f571b9197ebc610d8af8 to your computer and use it in GitHub Desktop.
Save hanchang/ba4f7e0efec7f571b9197ebc610d8af8 to your computer and use it in GitHub Desktop.
// BENCH
const NEW_TEMPLATE_INPUT: &str = r#"{"e":"depthUpdate","E":1571889248277,"T":1571889248276,"s":"BTCUSDT","U":390497796,"u":390497878,"pu":390497794,"b":[["7403.89","0.002"],["7403.90","3.906"],["7404.00","1.428"],["7404.85","5.239"],["7405.43","2.562"]],"a":[["7405.96","3.340"],["7406.63","4.525"],["7407.08","2.475"],["7407.15","4.800"],["7407.20","0.175"]]}"#;
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("Deserialize using serde", |b| {
b.iter(|| {
let _: BBO =
serde_json::from_str(NEW_TEMPLATE_INPUT).expect("Failed to deserialize JSON");
})
});
c.bench_function("Deserialize without serde", |b| {
b.iter(|| {
// Your function should go here
})
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
// Serde de
#[derive(Debug)]
pub struct BBO {
pub bid: (f64, f64),
pub ask: (f64, f64),
}
impl<'de> Deserialize<'de> for BBO {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct DepthUpdate {
#[serde(alias = "b")]
bid: Vec<Vec<String>>,
#[serde(alias = "a")]
ask: Vec<Vec<String>>,
}
let depth_update = DepthUpdate::deserialize(deserializer)?;
// Assuming the best bid and ask are the first elements in the bid and ask vectors
let bid = depth_update
.bid
.get(0)
.ok_or_else(|| de::Error::missing_field("bid"))?;
let ask = depth_update
.ask
.get(0)
.ok_or_else(|| de::Error::missing_field("ask"))?;
let bid_tuple = (
bid[0].parse::<f64>().map_err(de::Error::custom)?,
bid[1].parse::<f64>().map_err(de::Error::custom)?,
);
let ask_tuple = (
ask[0].parse::<f64>().map_err(de::Error::custom)?,
ask[1].parse::<f64>().map_err(de::Error::custom)?,
);
Ok(BBO {
bid: bid_tuple,
ask: ask_tuple,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment