10
0
mirror of https://github.com/QuantumPackage/qp2.git synced 2024-11-14 18:13:51 +01:00
QuantumPackage/ocaml/Progress_bar.ml

90 lines
2.0 KiB
OCaml
Raw Normal View History

2019-01-25 11:39:31 +01:00
type t =
{
title: string;
start_value: float;
cur_value : float;
end_value : float;
bar_length : int;
2019-03-13 13:02:29 +01:00
init_time : float;
2019-01-25 11:39:31 +01:00
dirty : bool;
2019-03-13 13:02:29 +01:00
next : float;
2019-01-25 11:39:31 +01:00
}
let init ?(bar_length=20) ?(start_value=0.) ?(end_value=1.) ~title =
{ title ; start_value ; end_value ; bar_length ; cur_value=start_value ;
2019-03-13 13:02:29 +01:00
init_time= Unix.time () ; dirty = false ; next = Unix.time () }
2019-01-25 11:39:31 +01:00
let update ~cur_value bar =
{ bar with cur_value ; dirty=true }
let increment_end bar =
{ bar with end_value=(bar.end_value +. 1.) ; dirty=false }
let clear bar =
Printf.eprintf " \r%!";
None
let increment_cur bar =
{ bar with cur_value=(bar.cur_value +. 1.) ; dirty=true }
let display_tty bar =
let percent =
100. *. (bar.cur_value -. bar.start_value) /.
(bar.end_value -. bar.start_value)
in
let n_hashes =
(Float.of_int bar.bar_length) *. percent /. 100.
|> Float.to_int
in
let hashes =
2019-03-13 13:02:29 +01:00
String.init bar.bar_length (fun i ->
2019-01-25 11:39:31 +01:00
if (i < n_hashes) then '#'
else ' '
)
in
let now =
2019-03-13 13:02:29 +01:00
Unix.time ()
2019-01-25 11:39:31 +01:00
in
let running_time =
2019-03-13 13:02:29 +01:00
now -. bar.init_time
2019-01-25 11:39:31 +01:00
in
2019-03-13 13:02:29 +01:00
Printf.eprintf "%s : [%s] %4.1f%% | %8.0f s\r%!"
2019-01-25 11:39:31 +01:00
bar.title
hashes
percent
2019-03-13 13:02:29 +01:00
running_time;
{ bar with dirty = false ; next = now +. 0.1 }
2019-01-25 11:39:31 +01:00
let display_file bar =
let percent =
100. *. (bar.cur_value -. bar.start_value) /.
(bar.end_value -. bar.start_value)
in
let running_time =
2019-03-13 13:02:29 +01:00
(Unix.time ()) -. bar.init_time
2019-01-25 11:39:31 +01:00
in
2019-03-13 13:02:29 +01:00
Printf.eprintf "%5.2f %% in %20.0f seconds \n%!"
2019-01-25 11:39:31 +01:00
percent
2019-03-13 13:02:29 +01:00
running_time;
{ bar with dirty = false ; next = (Unix.time ()) +. 10. }
2019-01-25 11:39:31 +01:00
let display bar =
if (not bar.dirty) then
bar
2019-03-13 13:02:29 +01:00
else if (Unix.time () < bar.next) then
2019-01-25 11:39:31 +01:00
bar
else
begin
if (Unix.isatty Unix.stdout) then
display_tty bar
else
display_file bar
end