Union assignment test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
#include <memory>

#include <math.h>

#include <cstdlib>

#define VAR 0

using namespace std;

struct lambda {
    union {
        long long I;
        struct {
            int i;
            int j;
        } kappa;
    };
};

int main() {
#if VAR == 0
    lambda l1, l2;

    l1.kappa.i = 1;
    l1.kappa.j = 2;

    cout << "l1: " << l1.kappa.i << " " << l1.kappa.j << endl;

    for (int i = 0; i != 100000000; ++i)
        l2.I = l1.I;

    cout << "l1: " << l2.kappa.i << " " << l2.kappa.j << endl;

#else
    lambda l1, l2;

    l1.kappa.i = 1;
    l1.kappa.j = 2;

    cout << "l1: " << l1.kappa.i << " " << l1.kappa.j << endl;

    for (int i = 0; i != 100000000; ++i) {
        l2.kappa.i = l1.kappa.i;
        l2.kappa.j = l1.kappa.j;
    }

    cout << "l1: " << l2.kappa.i << " " << l2.kappa.j << endl;
#endif

    return 0;
}


What the heck is this?

I have a union that has actual variables i and j.
The first variant is to copy both i and j.
The second variant is to copy I. Copying single I copies both i and j in a result (as 1 long long usually takes 8 bytes, 2 ints: 4 + 4 = 8)
My test gives same result for both cases, but the test itself is done wrong.
100000000 loop makes no sense to identify difference between these 2 cases, as the most run-time is the loop itself, as I understand. (On the other hand, if the difference is too small, who cares? ))) )

I will end it with 2 questions:
1. How to make a proper test?
2. Theoretically, is there any run-time difference between such 1 assignment and 2 assignments?
Last edited on
Topic archived. No new replies allowed.