Since I do research with F# (in particular, using F# interactive), I\'d like to have switchable \"print-when-in-debug\" function.
I can do
let dprint
I've been profiling my application and found that debug formatting causes significant performance issues. Debug formatting occurs on almost every string of the code, due to the nature of the application.
Obviously, this has been caused by kprintf
which unconditionally formats and then passes a string
to a predicate.
Finally, I came up with the following solution that may be useful for you:
let myprintf (format: Printf.StringFormat<_>) arg =
#if DEBUG
sprintf format arg
#else
String.Empty
#endif
let myprintfn (format: Printf.TextWriterFormat<_>) arg =
#if DEBUG
printfn format arg
#else
()
#endif
Usage is quite simple, and format checking works fine:
let foo1 = myprintf "foo %d bar" 5
let foo2 = myprintf "foo %f bar" 5.0
// can't accept int
let doesNotCompile1 = myprintf "foo %f bar" 5
// can't accept two arguments
let doesNotCompile2 = myprintf "foo %f bar" 5.0 10
// compiles; result type is int -> string
let bar = myprintf "foo %f %d bar" 5.0
You can use the kprintf
function, which formats a string using the standard syntax, but then calls a (lambda) function you specify to print the formatted string.
For example, the following prints the string if debug
is set and otherwise does nothing:
let myprintf fmt = Printf.kprintf (fun str ->
// Output the formatted string if 'debug', otherwise do nothing
if debug then printfn "%s" str) fmt