Skip to content

Commit

Permalink
Update fannkuch.jl for ~61x speedup
Browse files Browse the repository at this point in the history
Now based on Javascript. In general, the fastest js programs tend to be very C-like, and Julia maps C-like programs extremely fast, so I'm finding it's a good rule of thumb. Copy js and we come out really fast.
  • Loading branch information
quinnj committed Apr 25, 2013
1 parent 608185c commit e70a168
Showing 1 changed file with 65 additions and 59 deletions.
124 changes: 65 additions & 59 deletions examples/shootout/fannkuch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,74 @@
# fannkuch-redux benchmark
# https://shootout.alioth.debian.org/u32/performance.php?test=fannkuchredux
#
# Based on the Scala program
# Based on the Javascript program
#

# flips the first a[1] elements of a,
# assuming a is a permutation of the set {1, ..., length(a)}
flip(a) = [reverse(a[1:a[1]]), a[a[1]+1:end]]

function fannkuch(n)
perm = [1:n]
counts = map(int, zeros(n))
r = n+1
flips = 0
maxflips = 0
nperm = 0
checksum = 0
while r > 1
while (r != 2)
counts[r-1] = r-1
r -= 1
end

# count flips
flips = 0
p = copy(perm)
while (p[1] != 1)
p = flip(p)
flips += 1
end

if (flips > maxflips)
maxflips = flips
end
if nperm % 2 == 0
checksum += flips
else
checksum -= flips
end

go = true
while go
if r == n+1
println(checksum)
return maxflips
end
p0 = perm[1]
for i = 1:r-1
perm[i] = perm[i+1]
end
perm[r] = p0
counts[r] -= 1
if counts[r] > 0
go = false
else
r += 1
end
end

nperm += 1
end
maxflips
p = Array(Int32,n)
for i = 1:n
p[i] = i
end
q = copy(p)
s = copy(p)
sign = 1; maxflips = sum = 0
while true
q0 = p[1]
if q0 != 1
for i = 2:n
q[i] = p[i]
end
flips = 1
while true
qq = q[q0] #??
if qq == 1
sum += sign*flips
flips > maxflips && (maxflips = flips)
break
end
q[q0] = q0
if q0 >= 4
i = 2; j = q0-1
while true
t = q[i]
q[i] = q[j]
q[j] = t
i += 1
j -= 1
i >= j && break
end
end
q0 = qq
flips += 1
end
end
#permute
if sign == 1
t = p[2]
p[2] = p[1]
p[1] = t
sign = -1
else
t = p[2]
p[2] = p[3]
p[3] = t
sign = 1
for i = 3:n
sx = s[i]
if sx != 1
s[i] = sx-1
break
end
i == n && return maxflips
s[i] = i
t = p[1]
for j = 1:i
p[j] = p[j+1]
end
p[i+1] = t
end
end
end
end

if length(ARGS) >= 1
N = int(ARGS[1])
else
Expand Down

0 comments on commit e70a168

Please sign in to comment.