nim-lang / RFCs

A repository for your Nim proposals.
136 stars 23 forks source link

[SPEED] assert's should be used as optimization hints (eg: `likely` for branch prediction) instead of discarded #114

Closed timotheecour closed 5 years ago

timotheecour commented 6 years ago

in release with --assertions:off, instead of just discarding the assert, we should use it as optimization hint, eg transforming assert cond into likely(cond)

here's likely for reference:

template likely*(val: bool): bool =
  ## Hints the optimizer that `val` is likely going to be true.
  ##
  ## You can use this template to decorate a branch condition. On certain
  ## platforms this can help the processor predict better which branch is
  ## going to be run. Example:
  ##
  ## .. code-block:: nim
  ##   for value in inputValues:
  ##     if likely(value <= 100):
  ##       process(value)
  ##     else:
  ##       echo "Value too big!"
  ##
  ## On backends without branch prediction (JS and the nimscript VM), this
  ## template will not affect code execution.
  when nimvm:
    val
  else:
    when defined(JS):
      val
    else:
      likely_proc(val)
mratsim commented 6 years ago

But cond might not be used at all. It would complicate the compiler while the dev can just put the likely himself.

iterator zip(a, b: openarray[int]): (int, int) =
  assert a.len == b.len
  for i in 0 ..< a.len:
    yield (a[i], b[i])

Also likely is often placebo nowadays. After taking a single branch once the CPU branch predictor already takes that into account.

Araq commented 6 years ago

You can't use likely here (the condition is not evaluated at all!), you can use assume though. Except that Nim has no assume and it seems a bad idea for robust software.

Araq commented 5 years ago

Not gonna happen. assume is not the same as assert.