Skip to content

Instantly share code, notes, and snippets.

@PhilipWitte
Last active December 24, 2015 05:39
Show Gist options
  • Save PhilipWitte/6751956 to your computer and use it in GitHub Desktop.
Save PhilipWitte/6751956 to your computer and use it in GitHub Desktop.
import StrUtils, Times


type Vector = tuple[x, y, z, w:float]

# factories
proc new(x, y, z, w:float): Vector {.noSideEffect, noInit, inline.} =
  result.x = x
  result.y = y
  result.z = z
  result.w = w

proc new(this:var Vector, x, y, z, w:float) {.noSideEffect, inline.} =
  this.x = x
  this.y = y
  this.z = z
  this.w = w

proc new(T:typedesc[Vector], x, y, z, w:float): Vector {.noSideEffect, noInit, inline.} =
  result.new(x, y, z, w)

# operators
proc `+=`(this:var Vector, vec:Vector) {.noSideEffect, inline.} =
  this.x += vec.x
  this.y += vec.y
  this.z += vec.z
  this.w += vec.w

proc `-=`(this:var Vector, vec:Vector) {.noSideEffect, inline.}=
  this.x -= vec.x
  this.y -= vec.y
  this.z -= vec.z
  this.w -= vec.w

# misc
proc `$`(this:Vector): string =
  return
    $this.x & ", " &
    $this.y & ", " &
    $this.z & ", " &
    $this.w


# bechmark
proc main =
  const
    count = 10
  var
    a, b: Vector
    sum: float
    repeat = stdin.readLine().parseInt()
  
  a.new(0, 0, 0, 0)
  b.new(1, repeat.float, 1, 1)
  
  for c in 0 .. count:
    var start = cpuTime()
    for t in 0 .. repeat:
      a += b
      b -= a
    sum += (cpuTime() - start)
  
  echo a
  echo b
  echo "result: ", (sum / count)


main()
```

Running and entering a value of '1' Outputs:

7.0140873300000000e+08, 7.0140873300000000e+08, 7.0140873300000000e+08, 7.0140873300000000e+08 1.1349031700000000e+09, 1.1349031700000000e+09, 1.1349031700000000e+09, 1.1349031700000000e+09 result: 2.9999999999999644e-07

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment