Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to replace elements in array - C

Let's say we have an array of ints like this:

const int size = 100000; int array[size]; //set some items to 0 and other items to 1 

I'd like to replace all items that have value of 1 with another value, for example 123456. This can be trivially implemented with:

for(int i = 0; i < size ; i++){     if(array[i] != 0)          array[i] = 123456; } 

Out of curiosity, is there a faster way to do this, by some kind of x86 trickery, or is this the best code for the processor?

like image 289
Axarydax Avatar asked Apr 26 '13 07:04

Axarydax


People also ask

Can we change elements in array in C?

We can change the contents of array in the caller function (i.e. test_change()) through callee function (i.e. change) by passing the the value of array to the function (i.e. int *array). This modification can be effective in the caller function without any return statement.

How do you change all elements in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.


1 Answers

For your specific case where you initially have 0 and 1, the following might be faster. You'll have to bench mark it. You probably can't do much better with plain C though; you may need to dive into assembly if you want to take advantage of "x86 trickery" that may exist.

for(int i = 0; i < size ; i++){   array[i] *= 123456; } 

EDIT:

Benchmark code:

#include <time.h> #include <stdlib.h> #include <stdio.h>  size_t diff(struct timespec *start, struct timespec *end) {   return (end->tv_sec - start->tv_sec)*1000000000 + end->tv_nsec - start->tv_nsec; }  int main(void) {   const size_t size = 1000000;   int array[size];    for(size_t i=0; i<size; ++i) {     array[i] = rand() & 1;   }    struct timespec start, stop;    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);   for(size_t i=0; i<size; ++i) {     array[i] *= 123456;     //if(array[i]) array[i] = 123456;   }   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);    printf("size: %zu\t nsec: %09zu\n", size, diff(&start, &stop)); } 

my results:

Computer: quad core AMD Phenom @2.5GHz, Linux, GCC 4.7, compiled with

$ gcc arr.c -std=gnu99 -lrt -O3 -march=native 
  • if version: ~5-10ms
  • *= version: ~1.3ms
like image 51
Nicu Stiurca Avatar answered Oct 02 '22 17:10

Nicu Stiurca