1

I have never worked with bit operations in C, but now I need to, because I need my program to be CPU efficient.

I have a big array int *vwhich contains k, numbers (k is known) and my program will set each v[i] to zero, in an undefined order, and will store the index i in an array int *q. Before storing the index I have to check if the index is already in q, so I won't store it twice. This check takes up a lot of time. I was thinking of implementing a bitset k bits, each set to zero and when I add index i to q, I would also set the bit i from my bitset to one. Before that I need to check if the i bit is not already one. How can I do that?

I did check if other questions already have my answer, but I didn't understand very well since I'm new to programming.

Codor
  • 17,447
  • 9
  • 29
  • 56
greenro
  • 31
  • 6
  • 8
    `"I have never worked with bit operations in C, but now I need to, because I need my program to be CPU efficient."` Well then you should start by not using bit operations. They're slow and CPU-inefficient. The only reason you'd use a bitset instead of an array of bytes is to save memory. You'd have to require **a lot** of bits to make this worth your while. – Jonathon Reinhart Jan 19 '15 at 07:20
  • 3
    Addressing individual bits does not usually help performance. Perhaps you can explain at a higher level what you're trying to accomplish, not in terms of bits? – John Zwinck Jan 19 '15 at 07:21
  • 1
    "Before storing the index I have to check if the index is already in q, so I won't store it twice" – looks like the data structure you're looking for is a set. – The Paramagnetic Croissant Jan 19 '15 at 07:21
  • 1
    To be CPU efficient, you could just use an array of `int* v`, where each position has boolean semantics to indicate whether `i` is contained in the set, i.e. `v[i]` is `1` if `i` is contained in the set and `0` otherwise (or the other way round, whatever is more suitable). I would guess this to perform much better than indexing out individual bits. – Codor Jan 19 '15 at 07:27
  • What's the maximum value for `k` ? – user3386109 Jan 19 '15 at 07:36
  • After I left to school today I realised that my question was pretty stupid. What I wanted was to declare a char *a; a=malloc(k,sizeof(char));. This is my "bitset" and my algorithm is much faster now. Thank you for your answers. – greenro Jan 19 '15 at 14:43

0 Answers0