I have a camera which has a motor attached which I can rotate using a serial cable. I figured it would be fun to have this camera analyze the webcam shots and turn in any direction there was motion. I pulled out python and pygame, and created a prototype. Unfortunately, I can’t make python go very fast. I made two test cases, 1 in C and 1 in python, to figure out if it would be worthwhile to rewrite it:
array-speed-test.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
void compare_arrays(int **screen1, int **screen2)
{
int x;
int y;
int diff;
int mult;
for(x = 0; x < 1920; x++) {
for(y = 0; y < 1080; y++)
{
mult = screen1[x][y] * screen2[x][y];
diff = abs(screen1[x][y] - screen2[x][y]);
}
}
}
int main(int argc, char **argv)
{
srand(time(NULL));
printf("Generating arrays...\n");
int **screen1;
int **screen2;
int i = 0;
int j = 0;
struct timeval now;
struct timeval end;
int usecs_passed;
screen1 = malloc(1920 * sizeof(int *));
screen2 = malloc(1920 * sizeof(int *));
for(i = 0; i < 1920; i++)
{
screen1[i] = malloc(1080 * sizeof(int));
screen2[i] = malloc(1080 * sizeof(int));
}
for(i = 0; i < 1920; i++)
{
for(j = 0; j < 1080; j++)
{
screen1[i][j] = rand() % 255;
screen2[i][j] = rand() % 255;
}
}
printf("Comparing arrays...\n");
gettimeofday(&now, NULL);
compare_arrays(screen1, screen2);
gettimeofday(&end, NULL);
usecs_passed = end.tv_usec - now.tv_usec;
printf("Time passed: %dms\n", (usecs_passed / 1000));
for(i = 0; i < 1920; i++)
{
free(screen1[i]);
free(screen2[i]);
}
return 0;
}
And my python code:
array-speed-test.py
#!/usr/bin/python
import random
import time
from math import fabs
def generateArray():
array_to_gen = [None] * 1920
for i in range(0, 1920):
array_to_gen[i] = [None] * 1080
for x in range(0,1920):
for y in range(0, 1080):
array_to_gen[x][y] = random.randrange(0,255)
return array_to_gen
def compareArrays(screen1, screen2):
for x in range(0, 1920):
for y in range(0, 1080):
diff = fabs(screen1[x][y] - screen2[x][y])
combo = screen1[x][y] * screen2[x][y]
if __name__ == "__main__":
print "Generating arrays..."
screen1 = generateArray()
screen2 = generateArray()
print "Created two screens. Comparing..."
startTime = time.time()
compareArrays(screen1, screen2)
print "Time taken: " + str((time.time() - startTime) * 1000) + "ms"
So far, the C program runs in 25ms, while the python program consistently takes 1100ms. Might have to ditch python for real time analysis, unless someone wants to point out how I am doing this completely wrong (I am assuming the comments will be use Numpy?)


Python Commands Module