A new rabbit hole (AI art & music)

Github CoPilot just helped me get a 1000x speed improvement on my helpless python code :slight_smile:

The program generates a “sawtooth → triangle → ramp” wavetable.

Before (my first python program, copypasta mix from whoknowswhere): 53 sec

import numpy as np
import scipy.io.wavfile as scipy_io_wavfile
from scipy import signal
from time import process_time

t1_start = process_time()   # Start the stopwatch / counter

# Settings  
data = np.empty(0,dtype = np.float32)   # empty float32 array
sampleRate = 44100                      # of samples per second (standard)
numSamples = 2048                       # of samples per waveform
numWaves   = 128                         # of waveforms in wavetable
pi         = np.pi                      # the constant pi

# Define wavetable as function of time 0 <= t < 1
# and sawtooth maximum parameter 0 <= x < 1

def waves(t,x):
    return signal.sawtooth(2 * pi * t, x)

# Loop through waveforms in wavetable
for waveIndex in range(numWaves):
    x = waveIndex / numWaves

    # Loop through samples in waveform
    for sampleIndex in range(numSamples):
        t = sampleIndex / numSamples

        # Append new sample to array
        data = np.append(data,waves(t,x))

# Generate .wav file

scipy_io_wavfile.write("wavetable.wav", sampleRate, data.astype('float32'))

# Stop the stopwatch / counter
t1_stop = process_time()

# Elapsed time in seconds   
print("Elapsed time during the whole program in seconds:", t1_stop - t1_start)

entered """optimize [TAB]
got """optimize the code by using numpy array and vectorization of the code."""

and after some trial and error, using TAB to get line suggestions:

After CoPilot assistance: 0.05 sec

import numpy as np
import scipy.io.wavfile as scipy_io_wavfile
from scipy import signal
from time import process_time

t1_start = process_time()   # Start the stopwatch / counter

# Settings
sampleRate = 44100  # of samples per second (standard)
numSamples = 2048  # of samples per waveform
numWaves = 128  # of waveforms in wavetable
pi = np.pi  # the constant pi

# Define wavetable as function of time 0 <= t < 1
# and sawtooth maximum parameter 0 <= x < 1

def waves(t, x):
    return signal.sawtooth(2 * pi * t, x)

# Loop through waveforms in wavetable
x = np.linspace(0, 1, numWaves)
t = np.linspace(0, 1, numSamples)

# Loop through samples in waveform
data = np.empty(0, dtype=np.float32)  # empty float32 array
for waveIndex in range(numWaves):
    data = np.append(data, waves(t, x[waveIndex]))

# Generate .wav file

scipy_io_wavfile.write("wavetable.wav", sampleRate, data.astype('float32'))

# Stop the stopwatch / counter
t1_stop = process_time()

# Elapsed time in seconds   
print("Elapsed time during the whole program in seconds:", t1_stop - t1_start) 

2 Likes