pydantic / speedate

Fast and simple datetime, date, time and duration parsing for rust.
https://docs.rs/speedate/latest/speedate/
MIT License
199 stars 17 forks source link

You are advised to optimize format performance #16

Closed zhuxiujia closed 2 years ago

zhuxiujia commented 2 years ago

You are advised to optimize format performance this change Can improve format performance several times

for example: this code

write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)

to My Code

impl Display for LogDate {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
       let mut buf: [u8; 29] = *b"0000-00-00 00:00:00.000000000";

        buf[0] = b'0' + (self.year / 1000) as u8;
        buf[1] = b'0' + (self.year / 100 % 10) as u8;
        buf[2] = b'0' + (self.year / 10 % 10) as u8;
        buf[3] = b'0' + (self.year % 10) as u8;

        buf[5] = b'0' + (self.mon / 10) as u8;
        buf[6] = b'0' + (self.mon % 10) as u8;

        buf[8] = b'0' + (self.day / 10) as u8;
        buf[9] = b'0' + (self.day % 10) as u8;

        buf[11] = b'0' + (self.hour / 10) as u8;
        buf[12] = b'0' + (self.hour % 10) as u8;
        buf[14] = b'0' + (self.min / 10) as u8;
        buf[15] = b'0' + (self.min % 10) as u8;
        buf[17] = b'0' + (self.sec / 10) as u8;
        buf[18] = b'0' + (self.sec % 10) as u8;

        buf[19] = b'.';

        buf[20] = b'0' + (self.nano / 100000000) as u8;
        buf[21] = b'0' + (self.nano / 10000000 % 10) as u8;
        buf[22] = b'0' + (self.nano / 1000000 % 10) as u8;
        buf[23] = b'0' + (self.nano / 100000 % 10) as u8;
        buf[24] = b'0' + (self.nano / 10000 % 10) as u8;
        buf[25] = b'0' + (self.nano / 1000 % 10) as u8;
        buf[26] = b'0' + (self.nano / 100 % 10) as u8;
        buf[27] = b'0' + (self.nano / 10 % 10) as u8;
        buf[28] = b'0' + (self.nano % 10) as u8;

        f.write_str(std::str::from_utf8(&buf[..]).unwrap())
    }
}
samuelcolvin commented 2 years ago

Humm, but how slow is Display now?

If it's from 2ns to 0.1ns, I really don't think it's worth it.

also, could some of this be moved into a look to save somewhat on verbosity?

PR welcome and I'll review from there.

zhuxiujia commented 2 years ago

Humm, but how slow is Display now?

If it's from 2ns to 0.1ns, I really don't think it's worth it.

also, could some of this be moved into a look to save somewhat on verbosity?

PR welcome and I'll review from there.

this befor and after benchmark (from 343ns to 85ns/iter) 微信图片_20220710184428 微信图片_20220710184437

samuelcolvin commented 2 years ago

ok, PR welcome.

samuelcolvin commented 2 years ago

fixed by #17.