// run_native.ce — load a module both interpreted and native, compare speed
//
// Usage:
//   cell --dev run_native <module>
//
// Loads <module>.cm via use() (interpreted) and via shop.use_native() (native),
// runs both and compares results and timing.

var os = use('internal/os')
var fd = use('fd')
var shop = use('internal/shop')

if (length(args) < 1) {
  log.compile('usage: cell --dev run_native <module>')
  log.compile('  e.g. cell --dev run_native num_torture')
  return
}

var name = args[0]
if (ends_with(name, '.cm')) {
  name = text(name, 0, length(name) - 3)
}

// --- Test argument for function-returning modules ---
var test_arg = 5000000
if (length(args) > 1) {
  test_arg = number(args[1])
}

// --- Interpreted run ---
log.compile('--- interpreted ---')
var t1 = os.now()
var mod_interp = use(name)
var t2 = os.now()
var result_interp = null
if (is_function(mod_interp)) {
  log.compile('module returns a function, calling with ' + text(test_arg))
  t1 = os.now()
  result_interp = mod_interp(test_arg)
  t2 = os.now()
}
result_interp = result_interp != null ? result_interp : mod_interp
var ms_interp = (t2 - t1) / 1000000
log.compile('result: ' + text(result_interp))
log.compile('time:   ' + text(ms_interp) + ' ms')

// --- Native run ---
// Resolve to .cm path for shop.use_native()
var mod_path = name + '.cm'
if (!fd.is_file(mod_path)) {
  log.error('\nno ' + mod_path + ' found')
  return
}

log.compile('\n--- native ---')
var t3 = os.now()
var mod_native = shop.use_native(mod_path)
var t4 = os.now()
var result_native = null
if (is_function(mod_native)) {
  log.compile('module returns a function, calling with ' + text(test_arg))
  t3 = os.now()
  result_native = mod_native(test_arg)
  t4 = os.now()
}
result_native = result_native != null ? result_native : mod_native
var ms_native = (t4 - t3) / 1000000
log.compile('result: ' + text(result_native))
log.compile('time:   ' + text(ms_native) + ' ms')

// --- Comparison ---
log.compile('\n--- comparison ---')
var match = result_interp == result_native
var speedup = 0
log.compile('match:  ' + text(match))
if (ms_native > 0) {
  speedup = ms_interp / ms_native
  log.compile('speedup: ' + text(speedup) + 'x')
}
