Skip to content

Instantly share code, notes, and snippets.

@blotta
Last active March 1, 2017 05:32
Show Gist options
  • Save blotta/6ad2eaf80d5cee8ce47cf20bf91965c7 to your computer and use it in GitHub Desktop.
Save blotta/6ad2eaf80d5cee8ce47cf20bf91965c7 to your computer and use it in GitHub Desktop.
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define INPUT_NUM 500000000
struct timeval t1, t2, rate1, rate2;
void* thread_func(void* parameter){
unsigned long *p = (unsigned long*)parameter;
unsigned long rate;
float elap_ms;
gettimeofday(&rate1, NULL);
while(*p < INPUT_NUM){
gettimeofday(&rate2, NULL);
elap_ms = (rate2.tv_sec - rate1.tv_sec) *1000 + (rate2.tv_usec - rate1.tv_usec) / 1000;
rate = 1000 * *p / elap_ms;
printf("\r%d %%\trate: %lu %-15s", 100 * *p/INPUT_NUM, rate, "Hz" );
}
}
int main(){
pthread_t thread_handle;
unsigned long i;
double sum, iavg, oavg = 0;
float vol = 0.333f;
//input generator
printf("Allocating...");
int16_t* input = (int16_t *) malloc(sizeof(int16_t)*INPUT_NUM);
if (input==NULL){
printf("\nCould not allocate input");
exit(1);
}else{
printf("Done\n");
}
printf("\nGenerating...");
fflush(stdout);
srand(1234); //fixed seed
for (i =0; i < INPUT_NUM; i++) { // -32768 to 32767 => -2^15 to 2^15 - 1
input[i]=rand() % 65536 - 32768; //max = 65535 - 32768
sum +=input[i];
}
printf("Done\n");
printf("\n Input\n=======\n");
iavg = sum/INPUT_NUM;
printf("Average: %f\n",iavg);
printf("Fist 5 samples:");
for (i=0; i < 5; i++)
printf(" %d",input[i]);
printf("\n");
//process data
printf("\nProcessing...\n");
int ret = pthread_create(&thread_handle, 0, thread_func, &i );
if( ret != 0){
printf("Thread could not be created\n");
return 1;
}
///// main process block /////
gettimeofday(&t1, NULL);
for (i = 0; i < INPUT_NUM ; i++) {
input[i] *= vol;
}
gettimeofday(&t2, NULL);
///////////////////////////////
pthread_join(thread_handle, 0);
printf("\r100 %%\n");
sum = 0;
for(i=0; i < INPUT_NUM; i++){
sum+=input[i];
}
printf("\n Output \n========\n");
oavg = sum/INPUT_NUM;
printf("Average: %f\n", oavg);
printf("Fist 5 samples:");
for (i=0; i < 5; i++)
printf(" %d",input[i]);
printf("\n");
printf("\n Results\n=========\n");
printf("Average change: %.2f %%\n", 100*oavg/iavg);
float elapsed_ms = (t2.tv_sec - t1.tv_sec) *1000 +
(t2.tv_usec - t1.tv_usec) / 1000;
double or = (double)INPUT_NUM / (1000 * elapsed_ms);
printf("Overall Rate: %.3f MHz\n", or);
int elapsed_s = (int)elapsed_ms / 1000;
int elapsed_min = (int)elapsed_s / 60;
elapsed_s -= elapsed_min*60;
elapsed_ms -= elapsed_s*1000;
printf("%dmin %ds %.3f ms \n",elapsed_min, elapsed_s, elapsed_ms);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment