1 | #include <stdio.h> |
2 | #include <stdint.h> |
3 | #include <stdlib.h> |
4 | #include <string.h> |
5 | #include <sys/time.h> |
6 |
|
7 | uint64_t us(void) { |
8 | uint64_t us; |
9 | struct timeval lnm_current_time; |
10 | gettimeofday(&lnm_current_time, NULL); |
11 | us = (lnm_current_time.tv_sec * 1000000ULL + lnm_current_time.tv_usec); |
12 | return us; |
13 | } |
14 |
|
15 | uint8_t bit_read(uint8_t bytes[], uint8_t pos) { |
16 | return bytes[pos >> 3] >> (pos & 7) & 1; |
17 | } |
18 |
|
19 | void bit_toggle(uint8_t bytes[], uint8_t pos) { |
20 | // byte = pos >> 3 == pos / 8 |
21 | // bit = pos & 7 == pos % 8 |
22 | // bit_select = 1 << bit |
23 | bytes[pos >> 3] ^= 1 << (pos & 7); |
24 | } |
25 |
|
26 | void print(uint8_t bytes[], uint8_t byte_count) { |
27 | for (unsigned short pos = 0; pos < byte_count * 8; pos++) { |
28 | printf("%c", 48 + bit_read(bytes, pos)); |
29 | } |
30 | putchar('\n'); |
31 | } |
32 |
|
33 | int main(){ |
34 | uint64_t a = us(); |
35 | uint8_t byte_count = 8; |
36 | srand(a); |
37 | uint64_t iter = rand() % 10000000; |
38 | uint8_t bytes[byte_count]; |
39 | memset(bytes, 0, byte_count); |
40 | for (uint64_t i = 0; i < iter; i++) { |
41 | bit_toggle(bytes, (bytes[0] ^ i) & (byte_count * 8 - 1)); |
42 | } |
43 | print(bytes, byte_count); |
44 | uint64_t elapsed = us() - a; |
45 | printf("Time elapsed: %luus (%fus per operation)\n", elapsed, elapsed/(float)iter); |
46 | return 0; |
47 | } |
48 |
|