-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition.c
99 lines (86 loc) · 2.45 KB
/
partition.c
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <math.h>
#include <endian.h>
#include "shared.h"
#ifdef USE_STDIO
static FILE *outfile[MAXPARTITIONS];
#else
static int outfd[MAXPARTITIONS];
#endif
int main(int argc, char *argv[])
{
#ifdef PERF_DEBUG
struct timespec start;
int r = clock_gettime(CLOCK_MONOTONIC, &start);
assert(r == 0);
#endif
if(argc < 4) {
printf("Usage: %s INFILE BASENAME PARTITIONS\n", argv[0]);
return 0;
}
// Open input file
int npartitions = atoi(argv[3]);
assert(npartitions <= MAXPARTITIONS && npartitions > 1);
int infd = open(argv[1], O_RDONLY);
assert(infd != -1);
size_t fsize = filesize(argv[1]);
assert(fsize % sizeof(struct record) == 0);
size_t nrecords = fsize / sizeof(struct record);
// Open all output partitions
for(int i = 0; i < npartitions; i++) {
char fname[256];
snprintf(fname, 256, "%s.%u", argv[2], i);
#ifdef USE_STDIO
outfile[i] = fopen(fname, "w");
assert(outfile[i] != NULL);
int ret = setvbuf(outfile[i], malloc(STDIO_BUFFER_SIZE), _IOFBF,
STDIO_BUFFER_SIZE);
assert(ret == 0);
#else
outfd[i] = open(fname, O_CREAT | O_WRONLY | O_TRUNC, 0644);
assert(outfd[i] != -1);
#endif
}
struct record *input = mmap(NULL, fsize, PROT_READ, MAP_SHARED | MAP_POPULATE, infd, 0);
assert(input != MAP_FAILED);
#ifdef PERF_DEBUG
struct timespec setup;
r = clock_gettime(CLOCK_MONOTONIC, &setup);
assert(r == 0);
#endif
// Copy input to output range partitions
int divisor = ceil((float)(1ULL << 32) / (float)npartitions);
for(size_t i = 0; i < nrecords; i++) {
uint32_t outpart = be32toh(input[i].msb32) / divisor;
#ifdef USE_STDIO
size_t ret = fwrite(&input[i], sizeof(struct record), 1, outfile[outpart]);
assert(ret == 1);
#else
ssize_t ret = write(outfd[outpart], &input[i], sizeof(struct record));
assert(ret == sizeof(struct record));
#endif
}
#ifdef PERF_DEBUG
struct timespec end;
r = clock_gettime(CLOCK_MONOTONIC, &end);
assert(r == 0);
#endif
close(infd);
for(int i = 0; i < npartitions; i++) {
#ifdef USE_STDIO
fclose(outfile[i]);
#else
close(outfd[i]);
#endif
}
#ifdef PERF_DEBUG
struct timespec closetime;
r = clock_gettime(CLOCK_MONOTONIC, &closetime);
assert(r == 0);
float tsetup = ts2s(&setup) - ts2s(&start),
tpartition = ts2s(&end) - ts2s(&setup),
tclose = ts2s(&closetime) - ts2s(&end);
fprintf(stderr, "time(s): setup = %.2f, partition = %.2f, close = %.2f\n",
tsetup, tpartition, tclose);
#endif
return 0;
}