Inaccurate PWM Signal Frequency and Timing
it seems in the first picture that the two pulses have different duty cycles which is why it appears shifted. It looks like the 'on' part stays on for less time than the 'off' so your duty cycle is probably &lt;50 but your frequency might still be 40kHz.

I think the most accurate way of getting 40kHz just with a teensy is to use timer interrupts as Majenko suggested. Check out the documentation for it here, its pretty straight forward,you set the timer to go off every 12.5us and in the ISR simply toggle a digital pin and keep count of how many times you've toggled it. If your teensy needs to run other interrupts you should change the priority using myTimer.priority(number); to possibly give the 40kHz interrupt a higher priority. One thing, don't use digitalWrite in the ISR as its slow af, either try digitalWriteFast or use assembly language to toggle it as pointed by Majenko.

Alternatively you could use a 555 timer which is easy to setup and I'm pretty sure it's been used to gerate 40kHz at 50% duty cycle, although it might be a bit tricky finding the correct capacitor/resistor values if they're too small/non-standard. Then you would hook up the output of the 555 timer to whatever you're hooking it up to and also to a digital input pin on the micro. Then you would have to set an external interrupt on that pin so whenever the 555 goes high the interrupt on the pin would fire and you would keep track of how many pulses have been generated.

Alternatively, you could use a digital signal synthesizer. I used the ad9837 for one of my projects. It can generate something like 0-3Mhz with a 5Mhz external clock at a resolution of 0.02 which is pretty good. I've got an altium design for it if you don't want to buy the module and an adapted version of the adafruit miniGen library which works with teensy3.5 link. Then you'd need to do the same feedback loop as the 555 to keep track of how many pulses have been produced (or your way of waiting X microseconds). The module is actually pretty low power so you could power it from a digital pin and turn that pin on/off every second.

I think you should try the interrupt method first, as it's the easiest. Also, I get that you want 8 pulses evey one second but maybe for debugging purposes have the 40kHz pulse go constantly and change your scope to measure frequency so you can see how far off you are from 40khz.Then once you know you're actually getting 40khz have it run every 1second.