calls and functions and why fixed stack locals don’t work

so far we’ve only been writing statements at the top level of the program. there’s no notion of a callable chunk of code. with the introduction of functions in chapter 24, all the current top level states like the compiler, locals, and chunks / instructions are moved into function objects

previously with locals we were effectively operating in a single function world. this effectively meant that all locals were allocated at the beginning of the global call stack. with functions that each have their own local environments, the author introduces an early idea that was implemented by fortran where different functions had their own fixed set of locals

this works if there’s no recursion and i’ll demo an example that shows why fixed, separate slots break down once you start to recurse:

fun factorial(n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

factorial(3);

assume we give factorial its own fixed set of stack slots

Slot 0: parameter n
Slot 1: temporary result for multiplication (the value in slot 0 * factorial (slot 0 – 1))

now call factorial(2). this produces slot 0 = 2 and slot 1 = 2 * factorial(1)

then call factorial(1). this produces slot 0 = 1

OH CRAP, but that just overwrote slot 0 = 2 which we need to compute 2 * factorial (1) from the previous call. except now it ends up calling 1 * factorial(0) and screws up the entire expression

bob notes that fortran was able to get away with fixed stack slots simply because they didn’t support recursion!

lox vm local variables visualization

in chap 22 of crafting interpreters, bob nystrom walks through the implementation of local variables. it makes efficient use of memory by tracking local variable position and scope metadata during compilation phase and leveraging that to locate the correct value in the immediate proximity within the execution stack (where we expect all local variables to end up, unlike globals which are late bound and may be defined far away from where they’re actually used).

what i found most complicated about this chapter is the number of states you need to track and hold to understand how the compile and runtime stages work together. it helped me to write down a few essential states in trying to understand it, so i figured i translate those notes to some sort of visualization because i think it might help others too

here’s a visualization of the compile phase where we’re converting the tokens into a byte code instruction sequence (chunks). the arrow indicates the parse position where the vm is pointing to the source code and the variables on the right represent the state at that point.

side note: i didn’t bother doing character by character – i moved the arrow to positions where there are actually side-effects since not all tokens produce the sideeffects i actually care about for this demo.

and here is the runtime execution of the resulting byte code sequence. as you can see, the first thing that happens is that the literal number 13 is pushed onto the stack. every variable declaration’s value will be known at compile time.

however, notice that there is no information about what the name of that constant is. is 13 the value of “foo”? or something else? what’s cool about this implementation is that it doesn’t matter at this time because during the compilation phase, we’ve already figured out where that local is going to be on the stack for the variable foo. based on the information about locals and off sets in the previous phase, it’s going to be at position or offset 0 based on the metadata from the locals array that was getting constructed at compile time.

first half marathon and training plan

i’m planning on doing my first half marathon this year, the syracuse half marathon! i’m also going to be posting my training updates here, mostly for myself to refer to

the race is on march 23, so that’s 10-11 weeks from now. that’s plenty of time for a good training block. my A goal is to finish in 1:45 (about 8:03 mile pace, 25min 5k pace), my B goal is to finish in 1:50, and C goal is to finish just somewhere close to two hours (this is all based on my current threshold pace for 5k which i think is around 7:45 – 8:15 mpm) and keep it conservative.

training wise i’m adapting the novice marathon program in hal higdons Marathon Guide book for a half marathon. a couple of interesting parts of his training program is the long run mile step back every 3rd week and gradual increase of the mid week mileage. the purpose of the step back is to support recovery after a couple of consecutive mile increases before building back higher

unlike his program for the novice training instead of doing saturday long run i’m doing a sunday one followed by a recovery run. he also packs all three non-long runs together consecutively but i like having space between those runs for cross training / strength training or just rest – so i adjusted that too.

overall i’m optimistic about this program because it’s not too far off from my current weekly mileage and i’m coming off of a short break from running due to the weather lately, so i should adapt well to this but who knows. since i am going to be targeting a specific pace i know i need to throw some speed work and threshold runs in there so the breaks between runs mid week should help

here’s my full schedule (thanks claude ai for formatting my original csv into a table)

note: run 1 is following a long run, so that will be an easy run. run 2 and 3 will either both be easy if i’m not feeling great, but ideally one or both of them are threshold runs. will play it mostly by ear

WeekRun 1Run 2Run 3Long RunTotal Miles
1333615
2333716
3343717
4343515
5343919
63531021
7353718
83631224
93631022
10363820

for race pace and finish times i like to use this chart.

training log

i’m going to keep short updates here as i progress

1/15

  • training going well, been hitting the workouts and also did a tuesday short 45min group running training sesh (polymetrics mostly) at gym
  • today did a 3miler on treadmill, 10min warmp up and 10 cooldown with threshold pace in middle
  • TIL that 1% incline is good for imitating wind resistance friction for treadmill + lower knee impact. makes sense
  • form / mechanics notes: working on landing softer, more knee drive and less lower leg extension
  • pace feels a bit quick – will work on increasing incline but reducing pace
  • also may look into interleaving outdoor runs with treadmills at some point, weather permitting…

1/16

  • OK, so today i think i’m officially starting to overtrain…. i did a 1hr yoga at 5:30, 45min circuit training and sprinting at 8 followed by a 3 mile threshold. um my right foot ankle felt wonky and weird to put pressure on. i think i also laced my shoes too tight on the right
  • i ALSO tried a slightly different gait (shortening leg extension to land closer to my center of mass) at the same time, which honestly felt better
  • i made an effort to run more lightly on the treadmill today (focusing on reducing impact sound mostly) and my stride felt much smoother
  • anyway, im pretty much set with my mid week mileage (9 total so far) so im just gonna rest up for my long run over the weekend (6mi)

1/19

  • completed my first long run of the halfy training!! ran outdoors for 6.2 miles. most of the route i picked was pretty snow packed and my legs were sinking with each stride. left calf muscles and achilles feel pretty sore – not sure if snow or new shoes (lone peak altras) or both
  • i had to avoid sidewalks in a couple of .5 – 1 mile stretches and ran pretty close to threshold pace because i wanted to get off the road quickly
  • feeling good though, the snow def. forced me to slow down for most of it. got to get in a bit of hill work at beginning at end too. overall great workout

1/20

  • did a 3 miler today, started at easy pace and then did threshold for about a mile before dropping back to easy. good workout, but in future im going to try to hold the pace for the entire session, and reserve threshold workouts for specific days. it does seem like the treadmill picks up my HR reader so that’s good!

1/22

  • currently in week 2 of my training block. did a 5km with 3 1k repeats at 90-95% max HR . felt really tough, esp. towards the end. i actually cut short the last repeat by about 200m for sake of time and also i was at my limit
  • good workout, but i think maybe a shorter interval like 400m would be good followed by 30s to 1m rests in future
  • wore olympus via 2 for first time today, bought a used pair for 80 bucks off ebay. really loving this new model. the via 1 has a very stiff / firm sole, and they seemed to have incorporated that feedback. on their site: “It’s that same high stack but with a softer midsole foam”. really like it now! might retire my via 1’s

1/24

  • did my final midweek 3mi workout of week 2! really didn’t really feel like it because I didn’t sleep too well and its cold af. snow day and streets were a bit unplowed so I decided to scrap my original plan of going to the gym and instead go outside. wasn’t too bad, although starting earlier might be better because a lot of people around 7-8 were pulling out of their garages to go to work
  • did a fartlek workout with about 100m hill repeats 3 times . the entire run was pretty hilly , about 300ft elevation gain so 100ft / mile . pretty tough workout
  • felt slight ache on left knee (weirdly my right knee has not bothered me at all) that went away with a quad stretch. will keep an eye on

1/27

  • long run on sunday ended up being 8 mi instead of 7 b.c of wrong turn. felt good. went out a bit too fast. should stick to 10-9min miles. ended up in a snowy patch which wasn’t great and had to walk for safety reasons
  • need better gloves if im to do more outdoor running…
  • feeling good, did a 3mi on treaadmill this morning easy run with a short 3-4min tempo.

1/31

  • did a final three mile run today at the gym for the week. was not feeling very motivated and pretty fatigued, probably from not great sleep this week. watch tells me that my HRV is low. was supposed to do a workout but I just took it easy
  • for the four mile run earlier this week, I did 4 800 hundred meter repeats. that was a pretty good workout, ran pretty close to my max heart rate

running economy and vo2

running economy is a complicated topic and hard to measure, but a common measure of economy is done through vo2 (volume of oxygen) measures as a proxy. according to wikipedia, “Those who are able to consume less oxygen while running at a given velocity are said to have a better running economy”.

i put together a few visuals to illustrate this concept better.

here’s a graph showing

  • oxygen consumption or vo2 on the y axis
  • velocity in meters per second on the x axis
  • as velocity increases, so does oxygen consumption. they increase together up to a point (vo2 max)
  • oxygen consumption plateaus / steady states at the vo2max at and beyond a specific velocity

now, if the athletes is able to train their aerobic system to run at the same velocity with lower oxygen consumption, you get this graph

  • the dotted black vo2 consumption at given pace is the original line. the new solid line is as a result of training
  • same pace, but lower o2 consumption. this athlete has improved their running economy!
  • similarly, if you graph the relationship between vo2 and velocity for different athletes, the one with the lower vo2 consumption at any given pace is more economical

i also find this relationship interesting because it also tells you why increasing vo2 max is valuable. vo2 max sort of represents near maximum / max effort and running at vo2 max typically can’t really be sustained for longer than 11 minutes. right now, the athlete can only run at their max for 11 minutes. if you shift the max up, here’s what happens

  • the previous velocity is now a fraction of max, so less effort is required to sustain the same pace. they can now race at that same pace for longer! better endurance
  • the new max is associated with higher velocity. their previous 11 minute high effort pace is even faster

precise vo2 max testing is typically done in a lab hooked up to an mask that measures oxygen consumption while running on treadmill at increasing intensity. one of my favorite running youtubers / olympic athlete is luis orta (venezuelan runner). he does a vo2 max test here and gets an 80 mL/kg/min.

that is a ridiculous number because the average vo2 max for untrained individuals are around 30 – 40!

vo2 max at the end of the day is just a metric / one indicator. i used to see vo2 max videos everywhere on youtube when i first started running and it made me feel like i somehow needed to track it as part of my training. completely untrue.