Skip to content

Instantly share code, notes, and snippets.

@z-m-k
Created July 27, 2015 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z-m-k/e2b5b62218e3639ca135 to your computer and use it in GitHub Desktop.
Save z-m-k/e2b5b62218e3639ca135 to your computer and use it in GitHub Desktop.
Speeding up sandwiches in Julia
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"timeIt (generic function with 1 method)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"function timeIt(f, k)\n",
" f()\n",
" t=time()\n",
" for i=1:k\n",
" f()\n",
" end\n",
" t=time()-t\n",
" println(\"Average time \", t/k)\n",
"end"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"N=10\n",
"T=10000\n",
"X=randn(T,N);\n",
"u=randn(T);"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Average time 0.6659400010108948\n",
"Average time 0.6593200016021729\n",
"Average time 0.009630000591278077\n",
"true\n"
]
}
],
"source": [
"function get_V(X::Array{Float64, 2}, u::Array{Float64, 1})\n",
" return X'*diagm(u.^2)*X\n",
"end\n",
"\n",
"function get_V_oneLoop(X::Array{Float64, 2}, u::Array{Float64, 1})\n",
" Z=fill(0.0, N, T)\n",
" for i=1:T\n",
" @inbounds Z[:,i]=u[i]^2*X[i,:]\n",
" end\n",
" return Z*X\n",
"end\n",
" \n",
"f1()=get_V(X, u)\n",
"timeIt(f1, 100)\n",
"\n",
"f2()=X'*diagm(u.^2)*X\n",
"timeIt(f2, 100)\n",
"\n",
"f3()=get_V_oneLoop(X, u)\n",
"timeIt(f3, 100)\n",
"\n",
"println(get_V_oneLoop(X, u)==get_V(X, u))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 0.3.7",
"language": "julia",
"name": "julia-0.3"
},
"language_info": {
"name": "julia",
"version": "0.3.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment