-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.php
More file actions
90 lines (79 loc) · 2.05 KB
/
Copy pathexample.php
File metadata and controls
90 lines (79 loc) · 2.05 KB
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
<?php
/*
* Running the example program:
* $ php example.php
* filesize: 10000
* histogram: 0:40, ..., f:40, 10:39, ..., ff:39
* delta histogram: 1:9960, -255:39
*
* Without output buffering:
* $ strace php example.php 2>&1 | grep 'write(4' | wc -l
* 10000
*
* With output buffering:
* $ strace php example.php 2>&1 | grep 'write(4' | wc -l
* 3 # 4096 + 4096 + 1808 = 10000 bytes
*/
function calc_hist($contents, $fsize)
{
$hist = array_pad([], 256, 0);
for ($i = 0; $i < $fsize; $i++) {
$key = ord($contents[$i]);
$hist[$key]++;
}
return $hist;
}
function print_hist($hist)
{
$toks = [];
foreach ($hist as $key => $val) {
$toks[] = dechex($key) . ":$val";
}
echo 'histogram: ' . implode(', ', $toks) . "\n";
}
function calc_deltahist($contents, $fsize)
{
$deltahist = [];
for ($i = 1; $i < $fsize; $i++) {
$from = ord($contents[$i-1]);
$to = ord($contents[$i]);
$delta = $to - $from;
if (!isset($deltahist[$delta]))
$deltahist[$delta] = 0;
$deltahist[$delta]++;
}
return $deltahist;
}
function print_deltahist($deltahist)
{
$toks = [];
foreach ($deltahist as $key => $val) {
$toks[] = "$key:$val";
}
echo 'delta histogram: ' . implode(', ', $toks) . "\n";
}
$fname = '/tmp/example.txt';
$fp = fopen($fname, 'w');
/*
* Requires that extension=output_buffer is added to /etc/php/8.3/cli/php.ini
*/
stream_filter_append($fp, 'output.buffer');
/*
* This simulates some legacy/library code that does a lot of small
* writes and has a terrible performance but which we cannot easily
* change or don't want to touch for other reasons
*/
for ($i = 0; $i < 10000; $i++) {
fwrite($fp, chr($i));
}
fclose($fp);
echo "filesize: " . filesize($fname) . "\n"; // should be 10000
$handle = fopen($fname, 'r');
$fsize = filesize($fname);
$contents = fread($handle, $fsize);
fclose($handle);
$hist = calc_hist($contents, $fsize);
print_hist($hist);
$deltahist = calc_deltahist($contents, $fsize);
print_deltahist($deltahist);
?>