I would like to write a Real-time Audio to Pitch algorithm in Python and it looks like the Yin Algorithm solves this problem. I have found a number of C implementations of Yin, and having tried one of them out on my voice it works as expected and in real time. I have started porting it to Python but I can see that it is around 100 times slower - so no longer real.time. I am using a 2.3 GHz Quad-Core Intel Core i7.
Below is a simulation of the algorithm, in both C and Python, to give an idea of the computation involved. Each simulation is calculating the pitch for 90,000 samples. The C function takes 2 seconds and the Python 200 seconds to complete.
C code
#include <stdio.h>
#include <stdint.h>
#include <time.h>
int main(int argc, char** argv) {
int buffer_length = 150;
float sec = 0;
float* buffer = malloc(sizeof(float)*buffer_length);
clock_t before = clock();
int j;
int16_t tau;
int16_t i;
float delta;
for(j = 0; j < 90000; j++){
for(tau = 0 ; tau < 75; tau++){
for(i = 0; i < 75; i++){
delta = buffer[i] - buffer[i + tau];
buffer[tau] += delta * delta;
}
}
}
clock_t difference = clock() - before;
sec = difference / (float )CLOCKS_PER_SEC;
printf("%f\n",sec);
return 0;
}
Python code
import time
buffer = [0.0]*150
ts = time.time()
for j in range(90000):
for tau in range(75):
for i in range(75):
delta = buffer[i] - buffer[i + tau]
buffer[tau] += delta * delta
print(time.time()-ts)
I was thinking of using a sampling rate of 8KHz but possibly a higher rate if possible. Should it be possible to vastly improve the performance of the Python code and if so how would I go about doing this? If not, then I guess writing a C library with a Python Wrapper is my only option.
This looks like a job for numba. The issue is that python for loops are significantly slower than C loops. Using numba you should be able to speed them up quite dramatically since you've written them yourself and there are no external dependencies (which have been known to mess with numba).
Just use the njit decorator and wrap your nested for loops in a function.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments