-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.c
71 lines (47 loc) · 1.17 KB
/
util.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
#include <sys/time.h> // gettimeofday()
#include <stdio.h> // snprintf()
#include <stdlib.h> // rand()
#include <math.h> // log(), pow()
#include "util.h"
char* printsize(char* buffer, unsigned int length, uint64_t size) {
// floor(log(pow(2, 64)) / log(1024)) = 6
const char* unit[] = {
"B", "KB", "MB", "GB", "TB", "PB", "EB"
};
if (size == 0) {
snprintf(buffer, length, "0 %s", unit[0]);
} else {
unsigned int base = floor(log(size) / log(1024));
snprintf(buffer, length, "%.2f %s", size / pow(1024, base), unit[base]);
}
return buffer;
}
char* str_repeat(char* buffer, char c, unsigned int count) {
char* p = buffer;
for (unsigned int i = 0; i < count; ++i) {
*p++ = c;
}
return buffer;
}
uint32_t rand32() {
uint32_t r = 0;
for (int i = 0; i < 4; ++i) {
r |= (rand() & 0xFF) << (i * 8);
}
return r;
}
uint64_t rand64() {
uint64_t r = 0;
for (int i = 0; i < 8; ++i) {
r |= (rand() & 0xFF) << (i * 8);
}
return r;
}
int64_t ustime() {
struct timeval tv;
int64_t ust;
gettimeofday(&tv, NULL);
ust = ((int64_t)tv.tv_sec) * 1000000;
ust += tv.tv_usec;
return ust;
}