Currently, there is no way to access the time in milliseconds from an OCaml submission (e.g. gettimeofday()). This limits our ability to use the available processing time.
It’s currently possible to circumvent this by submitting a Python program which compiles and runs the OCaml program with unix.cmxa. Unfortunately this means the solution appears to be written in Python, which isn’t correct. Doing the same thing from OCaml requires… the Unix library.
Adding it is as simple as adding “unix.cmxa” to the compilation command. For example:
ocamlopt -o /tmp/solution unix.cmxa solution.ml
If we had Unix by default, a program like the following could compile and run any OCaml solution with any standard OCaml library it needs:
let answer = {answer|
let v = Unix.gettimeofday();;
print_endline (string_of_float v);;
|answer};;
let execv binary args =
Unix.create_process binary args Unix.stdin Unix.stdout Unix.stderr
;;
let () = (
let out_chan = open_out "/tmp/native_with_library.ml" in
Printf.fprintf out_chan "%s%!" answer;
ignore (Sys.command "ocamlopt -o /tmp/native_with_library unix.cmxa /tmp/native_with_library.ml");
ignore (execv "/tmp/native_with_library" [||])
);;
Some time ago, similar solutions were posted in this forum which used Sys.command instead of Unix.create_process. This doesn’t seem to work now, since Sys.command does not connect stdin and stdout to the child process.
If anyone else wants to use OCaml with libraries, this is the solution I’m usng in Python:
answer = """
let v = Unix.gettimeofday();;
print_endline (string_of_float v);;
"""
ocamlopt_location = "/usr/local/bin/ocamlopt"
import subprocess
import os
with open('/tmp/answer.ml', 'w') as f:
f.write(answer)
subprocess.call([ocamlopt_location, '-o', '/tmp/answer', 'unix.cmxa', '/tmp/answer.ml'])
os.execv('/tmp/answer', ['none'])
Here are some links to related topics:
It would be great if the CodinGame developers could add unix.cmxa to the OCaml compilation arguments, bringing it up to parity with other languages on the site.