Skip to content

Instantly share code, notes, and snippets.

@planetis-m
Created July 10, 2021 17:54
Show Gist options
  • Save planetis-m/a0d347c19c6ec41bc9e08c8ac9771d57 to your computer and use it in GitHub Desktop.
Save planetis-m/a0d347c19c6ec41bc9e08c8ac9771d57 to your computer and use it in GitHub Desktop.
from typetraits import supportsCopyMem
const
maxEntities* = 10_000
type
Array*[T] = object
data: ptr array[maxEntities, T]
proc `=destroy`*[T](x: var Array[T]) =
if x.data != nil:
when not supportsCopyMem(T):
for i in 0..<maxEntities: `=destroy`(x[i])
dealloc(x.data)
proc `=copy`*[T](dest: var Array[T], src: Array[T]) {.error.}
template initImpl(result: typed) =
result.data = cast[typeof(result.data)](alloc(maxEntities * sizeof(T)))
proc initArray*[T](): Array[T] =
initImpl(result)
template checkInit() =
when compileOption("boundChecks"):
assert x.data != nil, "array not inititialized"
template get(x, i) =
checkInit()
x.data[i]
proc `[]`*[T](x: Array[T]; i: Natural): lent T =
get(x, i)
proc `[]`*[T](x: var Array[T]; i: Natural): var T =
get(x, i)
proc `[]=`*[T](x: var Array[T]; i: Natural; y: sink T) =
#checkInit()
if x.data == nil: initImpl(x)
x.data[i] = y
proc clear*[T](x: Array[T]) =
when not supportsCopyMem(T):
if x.data != nil:
for i in 0..<maxEntities: reset(x[i])
template toOpenArray*(x, first, last: typed): untyped =
toOpenArray(x.data, first, last)
import heaparrays, std/times
proc addReverse*(result: var Array[char], a: openArray[char]) =
let offset = maxEntities - 1
for i in 0..<maxEntities:
result[offset-i] = a[i]
proc main =
var s: Array[char] = initArray[char]()
var c = 0
var x: Array[char] = initArray[char]()
let M = maxEntities
let n = 1_000_000
for i in 0..<M: x[i] = cast[char](i)
let K = 1 shl 5 - 1
let t = cpuTime()
for i in 0..<n:
# generate an un-predictable 2nd argument
addReverse(s, x.toOpenArray(i and K, (i and K) + M - 1))
c+=int(s[3])
let t2 = cpuTime()
echo (c, t2 - t)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment