janestreet / base

Standard library for OCaml
MIT License
848 stars 124 forks source link

Expose Array.create_float from stdlib #120

Closed mbacarella closed 2 years ago

mbacarella commented 2 years ago

The standard library provides Array.create_float, though it does not appear re-exported in Base.

This is substantially faster than creating a float array using Base's Array.create ~len 0., and also gives you the option of initializing it by yielding periodically to, say, Async. This is very important for low-latency, realtime applications as it prevents Async from being blocked.

This PR proposes exposing the stdlib create_float function, but with a more appropriate name: create_float_uninitialized.

A quick benchmark follows:

open! Base
open Stdlib.Printf

let timeit ~name ~times ~f =
  let t1 = Unix.gettimeofday () in
  for _i=0 to Int.pred times; do
    f ();
  done;
  let t2 = Unix.gettimeofday () in
  printf "[%s] x%d = %fs\n" name times (t2 -. t1)

let () =
  let len = 1000000 in
  let timeit = timeit ~times:1000 in
  timeit ~name:(sprintf "Array.create ~len:%d 0." len)
    ~f:(fun () ->
    let a = Array.create ~len 0. in
    a.(0) <- 1.0);

  timeit ~name:(sprintf "Array.create_float_uninitialized %d" len) ~f:(fun () ->
    let a = Array.create_float_uninitialized len in
    a.(0) <- 1.0)
% dune exec ./test_base.exe
[Array.create ~len:1000000 0.] x1000 = 1.549169s
[Array.create_float_uninitialized 1000000] x1000 = 0.085484s
aalekseyev commented 2 years ago

@mbacarella, can you please sign-off your contribution as described in https://probot.github.io/apps/dco/?

mbacarella commented 2 years ago

@mbacarella, can you please sign-off your contribution as described in https://probot.github.io/apps/dco/?

I think adding a DCO will leave a big mess in the repo since I have the rebase in master in this PR. Do you know a clean way to do this, or should I just submit a new PR that's properly signed off?

aalekseyev commented 2 years ago

You can git rebase the commits. E.g. you could use git rebase -i 02baffc343fd0eb8f58dce6fddf1ab5d3afba78e (and only keep the meaningful commit in the resulting prompt). Making a new PR is also fine.

aalekseyev commented 2 years ago

Thank you!

aalekseyev commented 2 years ago

cc @lpw25, given your involvement with Float_array (which is not open-source (yet?)).