-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcountbits.c
1464 lines (1291 loc) · 42.3 KB
/
tcountbits.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <sys/cdefs.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
/*
* Counting bits set in an integer (i.e. calculating the integer's Hamming
* Weight) as an excercise in benchmarking small algorithms using getrusage(2)
*
* for info about the worker algorithms used here see these pages:
* <URL:http://graphics.stanford.edu/~seander/bithacks.html>
* <URL:http://gurmeet.net/puzzles/fast-bit-counting-routines/>
*/
/*
* WARNING: time can appear to have gone backwards with getrusage(2)!
*
* See NetBSD Problem Report #30115 (and PR#10201).
* See FreeBSD Problem Report #975 (and PR#10402).
*
* Problem has existed in all *BSDs since 4.4BSD if not earlier.
*
* Only FreeBSD has implemented a "fix" (as of rev.1.45 (svn r44725) of
* kern_resource.c (etc.) on April 13, 1999)
*
* But maybe it is even worse than that -- distribution of time between user
* and system doesn't seem to match reality!
*
* See the GNU MP Library (GMP)'s tune/time.c code for better timing?
*/
/*
* do nothing much, but make sure you do it!
*/
unsigned int nullfunc(unsigned long);
unsigned int
nullfunc(unsigned long val)
{
return (unsigned int) val;
}
/*
* return the number of bits set to one in a value
*
* K&R, 1st Ed. 1978, page 47
*
* The only optimization here is to cut the loop short when all the remaining
* high-order bits (that were not shifted in) are zeros.
*/
unsigned int bitcount(unsigned long);
unsigned int
bitcount(unsigned long val)
{
unsigned int bc;
for (bc = 0; val != 0; val >>= 1) {
if (val & 01) {
bc++;
}
}
return bc;
}
/*
* return the number of bits set to one in a value
*
* K&R another way -- most compilers should generate the exact same code
*/
unsigned int bitcount2(unsigned long);
unsigned int
bitcount2(unsigned long val)
{
unsigned int bc = 0;
while (val) {
bc += (unsigned int) (val & 01);
val >>= 1;
}
return bc;
}
/*
* return the number of bits set to one in a value
*
* Subtraction of 1 from a number toggles all the bits (from right to left) up
* to and including the righmost set bit.
*
* So, if we decrement a number by 1 and do a bitwise and (&) with itself
* ((n-1) & n), we will clear the righmost set bit in the number.
*
* Therefore if we do this in a loop until we're left with zero and count the
* number of iterations then we get the count of set bits.
*
* Executes in O(n) operations where n is number bits set to one in a given
* integer value.
*
* From http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
*
* Brian Kernighan's method goes through as many iterations as there are
* set bits. So if we have a 32-bit word with only the high bit set, then
* it will only go once through the loop.
*
* Published in 1978, in the C Programming Language 2nd Edition. (by Brian
* W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On
* April 19, 2006 Don Knuth pointed out to me that this method "was first
* published by Peter Wegner in CACM Vol 3 (1960), No 5, p 322. (Also
* discovered independently by Derrick Lehmer and published in 1964 in a
* book edited by Beckenbach.)"
*/
unsigned int countbits_sparse(unsigned long);
unsigned int
countbits_sparse(unsigned long val)
{
unsigned int bc = 0;
while (val) {
val &= val - 1; /* clear the least significant bit set to one */
bc++;
}
return bc;
}
/*
* another way -- most compilers should generate the exact same code
*/
unsigned int countbits_sparse2(unsigned long);
unsigned int
countbits_sparse2(unsigned long val)
{
unsigned int bc; /* bc accumulates the # of bits set in v */
for (bc = 0; val; bc++) {
val &= val - 1; /* clear the least significant bit that is set */
}
return bc;
}
/*
* optimized, in theory, for cases where most bits are set
*
* Executes in O(n) operations where n is number bits set to zero in a given
* integer value.
*/
unsigned int countbits_dense(unsigned long);
unsigned int
countbits_dense(unsigned long val)
{
unsigned int bc = sizeof(val) * CHAR_BIT;
for (val ^= ~0UL; val; bc--) {
val &= val - 1; /* clear the least significant bit that is set */
}
return bc;
}
/*
* most efficient non-lookup variant from the URL above....
*/
#define COUNT_BITS(T, x, c) \
{ \
T n = (x); \
\
n = n - ((n >> 1) & ~((T) 0) / 3); \
n = (n & ~((T) 0) / 15 * 3) + ((n >> 2) & ~((T) 0) / 15 * 3); \
n = (n + (n >> 4)) & ~((T) 0) / 255 * 15; \
c = (unsigned int) ((n * (~((T) 0) / 255)) >> ((sizeof(T) - 1) * CHAR_BIT)); \
} \
unsigned int count_bits(unsigned long);
unsigned int
count_bits(unsigned long val)
{
unsigned int bc;
COUNT_BITS(unsigned long, val, bc)
return bc;
}
/*
* Unattributed quote apparently by Don Gillies:
*
* I wrote a fast bitcount macro for RISC machines in about 1990[[!?!?!?!?]].
* It does not use advanced arithmetic (multiplication, division, %), memory
* fetches (way too slow), branches (way too slow), but it does assume the CPU
* has a 32-bit barrel shifter (in other words, >> 1 and >> 32 take the same
* amount of cycles.) It assumes that small constants (such as 6, 12, 24) cost
* nothing to load into the registers, or are stored in temporaries and reused
* over and over again.
*
* With these assumptions, it counts 32 bits in about 16 cycles/instructions on
* most RISC machines. Note that 15 instructions/cycles is close to a lower
* bound on the number of cycles or instructions, because it seems to take at
* least 3 instructions (mask, shift, operator) to cut the number of addends in
* half, so log_2(32) = 5, 5 x 3 = 15 instructions is a quasi-lowerbound.
*
* Here is a secret to the first and most complex step:
*
* input output
* AB CD Note
* 00 00 = AB
* 01 01 = AB
* 10 01 = AB - (A >> 1) & 0x1
* 11 10 = AB - (A >> 1) & 0x1
*
* so if I take the 1st column (A) above, shift it right 1 bit, and subtract it
* from AB, I get the output (CD). The extension to 3 bits is similar; you can
* check it with an 8-row boolean table like mine above if you wish.
*
* Don Gillies
*
* Newsgroups: comp.compression.research,comp.arch,comp.lang.c
* Path: mips!sdd.hp.com!ux1.cso.uiuc.edu!m.cs.uiuc.edu!gillies
* From: gillies@m.cs.uiuc.edu (Don Gillies)
* Subject: Re: Algorithm for finding set bits in a bit-string (and MSB).
* Message-ID: <1992Aug3.164044.28037@m.cs.uiuc.edu>
* Organization: University of Illinois, Dept. of Comp. Sci., Urbana, IL
* References: <1992Jul26.010325.9885@infonode.ingr.com>
* <MOSS.92Jul25222337@ibis.cs.umass.edu>
* <Bs3yBx.7AA@watserv1.uwaterloo.ca>
* <Bs46JC.35n@watcgl.uwaterloo.ca>
* Date: Mon, 3 Aug 1992 16:40:44 GMT
* Lines: 30
*
* What about using this algorithm to find the lowest bit set in a word
*
* if (p & (p-1)) return(-1); (* returns -1 if > 1 bit set *)
* return(bitcount(p ^ (p-1))); (* use XOR, returns 32 if no bit set *)
*
* where bitcount counts the number of bits in a word? bitcount exists
* in the hardware of several cdc machines and elsewhere. On other
* machines, it can be implemented in 16 arithmetic ops or much less if
* the computer has a fast % (remainder) operation. For instance, on the
* 68020 % is slow enough that the arithmetic bitcount() subroutine is
* faster. In fact, arithmetic bitcount can run faster than 8-bit
* character lookups (assuming a memory lookup is 2 cycles, whereas an
* arithmetic op is one cycle). Table lookups only win with 16-bit
* tables:
*
* bitcount(n)
* long unsigned n;
* {
* long unsigned tmp;
* tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);
* tmp = ((tmp + (tmp >> 3)) & 030707070707);
* tmp = (tmp + (tmp >> 6));
* tmp = (tmp + (tmp >> 12) + (tmp >> 24)) & 077;
* (* 6+3+3+5 = 16 ops *)
* --
*
* Also:
*
* According to Donald Knuth ("The Art of Computer Programming", Vol IV, p 11),
* the code first appeared in the first textbook on programming, "The
* Preparation of Programs for an Electronic Digital Computer" by Maurice
* Vincent Wilkes, David J. Wheeler, and Stanley Gill (Addison-Wesley Press, 2nd
* Edition, 1957).
*
* Pages 191–193 of the book presented Nifty Parallel Count by D B Gillies and
* J C P Miller.
*/
#define BitCount(X, Y) \
(Y = X - ((X >> 1) & 033333333333UL) \
- ((X >> 2) & 011111111111UL), \
Y = ((Y + (Y >> 3)) & 030707070707UL), \
Y = (Y + (Y >> 6)), \
Y = (Y + (Y >> 12) + (Y >> 24)) & 077UL)
unsigned int count_bits_risc(unsigned long);
unsigned int
count_bits_risc(unsigned long val)
{
unsigned long bc;
BitCount(val, bc);
return (unsigned int) bc;
}
/*
* fortune(6): -- really weird C code to count the number of bits in a word
*
* a variation on Gillies & Miller's algorithm?
*/
#define FORTUNE_BITCOUNT(x) (((BX_(x) + (BX_(x) >> 4)) & 0x0F0F0F0FUL) % 255)
#define BX_(x) ((x) - (((x) >> 1) & 0x77777777UL) \
- (((x) >> 2) & 0x33333333UL) \
- (((x) >> 3) & 0x11111111UL))
unsigned int count_bits_fortune(unsigned long);
unsigned int
count_bits_fortune(unsigned long val)
{
unsigned long bc;
bc = FORTUNE_BITCOUNT(val);
return (unsigned int) bc;
}
/*
* Parallel Count carries out bit counting in a parallel fashion. Consider n
* after the first line has finished executing. Imagine splitting n into pairs
* of bits. Each pair contains the "number of ones" in those two bit positions
* in the original n. After the second line has finished executing, each
* nibble contains the "number of ones" in those four bits positions in the
* original n. Continuing this for five iterations, the 64 bits contain the
* number of ones among these sixty-four bit positions in the original n. That
* is what we wanted to compute.
*/
#define TWO(c) (0x1u << (c))
#define MASK(c) (((unsigned int) (-1)) / (TWO(TWO(c)) + 1u))
#define COUNT(x,c) ((x) & MASK(c)) + (((x) >> (TWO(c))) & MASK(c))
unsigned int parallel_bitcount(unsigned long);
unsigned int
parallel_bitcount(unsigned long val)
{
val = COUNT(val, 0);
val = COUNT(val, 1);
val = COUNT(val, 2);
val = COUNT(val, 3);
val = COUNT(val, 4);
/* val = COUNT(val, 5) ; for 64-bit integers */
return (unsigned int) val;
}
/*
* Nifty Parallel Count works the same way as Parallel Count for the first
* three iterations. At the end of the third line (just before the return),
* each byte of n contains the number of ones in those eight bit positions in
* the original n. A little thought experiment then explains why the remainder
* modulo 255 works.
*/
#define MASK_01010101 (((unsigned int) (-1)) / 3)
#define MASK_00110011 (((unsigned int) (-1)) / 5)
#define MASK_00001111 (((unsigned int) (-1)) / 17)
unsigned int nifty_bitcount(unsigned long);
unsigned int
nifty_bitcount(unsigned long val)
{
val = (val & MASK_01010101) + ((val >> 1) & MASK_01010101);
val = (val & MASK_00110011) + ((val >> 2) & MASK_00110011);
val = (val & MASK_00001111) + ((val >> 4) & MASK_00001111);
return (unsigned int) (val % 255UL);
}
/*
* MIT Bitcount
*
* Consider a 3 bit number as being
* 4a+2b+c
* if we shift it right 1 bit, we have
* 2a+b
* subtracting this from the original gives
* 2a+b+c
* if we shift the original 2 bits right we get
* a
* and so with another subtraction we have
* a+b+c
* which is the number of bits in the original number.
*
* Suitable masking allows the sums of the octal digits in a 32 bit number to
* appear in each octal digit. This isn't much help unless we can get all of
* them summed together. This can be done by modulo arithmetic (sum the digits
* in a number by molulo the base of the number minus one) the old "casting out
* nines" trick they taught in school before calculators were invented. Now,
* using mod 7 wont help us, because our number will very likely have more than
* 7 bits set. So add the octal digits together to get base64 digits, and use
* modulo 63. (Those of you with 64 bit machines need to add 3 octal digits
* together to get base512 digits, and use mod 511.)
*
* This is HACKMEM 169, as used in X11 sources.
* Source: MIT AI Lab memo, late 1970's.
*
* works for 32-bit numbers only
*/
unsigned int mit_bitcount(unsigned long);
unsigned int
mit_bitcount(unsigned long val)
{
register unsigned long tmp;
tmp = val - ((val >> 1) & 033333333333UL)
- ((val >> 2) & 011111111111UL);
return (unsigned int) (((tmp + (tmp >> 3)) & 030707070707UL) % 63UL); /* 63 = 077 = 0x3F */
}
static unsigned char _bitCountTable8[1 << CHAR_BIT];
static bool _lookupTable8_Initialized = false;
#define defaultBitCount count_bits_risc
static void _initBitCountTable8(void);
static void
_initBitCountTable8(void)
{
unsigned long i;
if (_lookupTable8_Initialized) {
return;
}
for (i = 1; i < (1 << CHAR_BIT); i++) {
#if 1
_bitCountTable8[i] = (unsigned char) (_bitCountTable8[i >> 1] + (i & 1));
#else
_bitCountTable8[i] = (unsigned char) defaultBitCount(i);
#endif
}
_lookupTable8_Initialized = true;
return;
}
/*
* Look up each byte (uchar-sized hunk) of the value in a lookup table.
*/
unsigned int table_8_BitCount(unsigned long);
unsigned int
table_8_BitCount(unsigned long val)
{
unsigned int bc = 0;
#if 0
if (!_lookupTable8_Initialized) {
_initBitCountTable8();
}
#endif
/* here we terminate early if all that remains are zero-bytes */
while (val) {
bc += _bitCountTable8[val & UCHAR_MAX];
val >>= CHAR_BIT;
}
return bc;
}
/*
* unrolled version
*/
unsigned int table_8_BitCount2(unsigned long);
unsigned int
table_8_BitCount2(unsigned long val)
{
#if 0
if (!_lookupTable8_Initialized) {
_initBitCountTable8();
}
#endif
return (unsigned int) (_bitCountTable8[val & UCHAR_MAX] +
_bitCountTable8[(val >> CHAR_BIT) & UCHAR_MAX] +
_bitCountTable8[(val >> CHAR_BIT * 2) & UCHAR_MAX] +
_bitCountTable8[(val >> CHAR_BIT * 3) & UCHAR_MAX]);
}
static unsigned char _bitCountTable16[(1U << 16) +1];
static bool _lookupTable16_Initialized = false;
static void _initBitCountTable16(void);
static void
_initBitCountTable16(void)
{
unsigned long i;
if (_lookupTable16_Initialized) {
return;
}
for (i = 1; i <= (1U << 16); i++) {
#if 1
_bitCountTable16[i] = (unsigned char) (_bitCountTable16[i >> 1] + (i & 1));
#else
_bitCountTable16[i] = (unsigned char) defaultBitCount(i);
#endif
}
_lookupTable8_Initialized = true;
return;
}
/*
* Look up each byte (uchar-sized hunk) of the value in a lookup table.
*/
unsigned int table_16_BitCount(unsigned long);
unsigned int
table_16_BitCount(unsigned long val)
{
unsigned int bc = 0;
#if 0
if (!_lookupTable16_Initialized) {
_initBitCountTable16();
}
#endif
/* here we terminate early if all that remains are zero-bytes */
while (val) {
bc += _bitCountTable16[val & UINT16_MAX];
val >>= 16;
}
return bc;
}
/*
* unrolled version
*/
unsigned int table_16_BitCount2(unsigned long);
unsigned int
table_16_BitCount2(unsigned long val)
{
#if 0
if (!_lookupTable16_Initialized) {
_initBitCountTable16();
}
#endif
return (unsigned int) (_bitCountTable16[val & UINT16_MAX] +
_bitCountTable16[(val >> 16) & UINT16_MAX]);
}
#if 0
void
verify_bitcounts(unsigned long val)
{
unsigned int iterated_ones, sparse_ones, dense_ones;
unsigned int precomputed_ones, precomputed16_ones;
unsigned int parallel_ones, nifty_ones;
unsigned int mit_ones;
iterated_ones = iterated_bitcount (val);
sparse_ones = sparse_ones_bitcount (val);
dense_ones = dense_ones_bitcount (val);
precomputed_ones = precomputed_bitcount (val);
precomputed16_ones = precomputed16_bitcount (val);
parallel_ones = parallel_bitcount (val);
nifty_ones = nifty_bitcount (val);
mit_ones = mit_bitcount (val);
if (iterated_ones != sparse_ones) {
errx(1, "ERROR: sparse_bitcount (0x%x) not okay!\n", x);
}
if (iterated_ones != dense_ones) {
errx(1, "ERROR: dense_bitcount (0x%x) not okay!\n", x);
}
if (iterated_ones != precomputed_ones) {
errx(1, "ERROR: precomputed_bitcount (0x%x) not okay!\n", x);
}
if (iterated_ones != precomputed16_ones) {
errx(1, "ERROR: precomputed16_bitcount (0x%x) not okay!\n", x);
}
if (iterated_ones != parallel_ones) {
errx(1, "ERROR: parallel_bitcount (0x%x) not okay!\n", x);
}
if (iterated_ones != nifty_ones) {
errx(1, "ERROR: nifty_bitcount (0x%x) not okay!\n", x);
}
if (mit_ones != nifty_ones) {
errx(1, "ERROR: mit_bitcount (0x%x) not okay!\n", x);
}
return;
}
#endif
/* XXX see also timevalsub() */
suseconds_t difftval(struct timeval, struct timeval);
suseconds_t
difftval(struct timeval tstart, struct timeval tend)
{
tend.tv_sec -= tstart.tv_sec;
tend.tv_usec -= tstart.tv_usec;
/*
* be extremely careful that any over/under "impossible" tv_usec
* values from the above subtractions or earlier are ironed out and it
* is always left in range.
*
* XXX instead of a loop we could/should use '/' and '%', if this is
* right:
*
* if (tend.tv_usec < 0) {
* tv_sec -= (abs(tv_usec) / 1000000) + 1;
* tv_usec = 1000000 - (abs(tv_usec) % 1000000);
* }
* if (tend.tv_usec >= 1000000) {
* tv_sec += tv_usec / 1000000;
* tv_usec = tv_usec % 1000000;
* }
*/
while (tend.tv_usec < 0) {
tend.tv_sec--;
tend.tv_usec += 1000000;
}
while (tend.tv_usec >= 1000000) {
tend.tv_sec++;
tend.tv_usec -= 1000000;
}
return (suseconds_t) ((tend.tv_sec * 1000000) + tend.tv_usec);
}
/*
* Timing anomalies
*
* time(1) uses gettimeofday() to show the "real" time, by which it means the
* wall-clock time it took to run the process, including the time to do the
* vfork() and execvp(), ignore some signals, and call wait4().
*
* However currently on NetBSD because of the bogus way 4BSD has approximately
* always divied up time between user time and system time we can see
* getrusage() report a total of system plus user time of as much as 0.06
* seconds longer than gettimeofay() says it took for the whole thing! E.g.:
*
* $ /usr/bin/time -p false
* real 0.00
* user 0.03
* sys 0.03
*
* Furthermore gettimeofday() can wander, e.g. due to NTP, or worse.
*
* Use the POSIX.1b-1993 clock_gettime(CLOCK_MONOTONIC, tspec) instead if possible!
*
* WARNING: apparently the Linux folks mis-read the POSIX.1b specifications
* and/or didn't understand the definition of a monotonically increasing time
* clock, and their CLOCK_MONOTONIC clock is affected by system time
* adjustments, so you have to use their invented non-standard
* CLOCK_MONOTONIC_RAW clock to get a real monotonic time clock. Note too that
* some sources claim CLOCK_MONOTONIC_RAW sometiems produces garbage results,
* and is also significantly more expensive to call [1].
*
* On the other hand note that CLOCK_MONOTONIC is only subject to incremental
* corrections, not sudden jumps, so CLOCK_MONOTONIC_RAW would be relevant
* mainly to cases where more accurate time is wanted over very short intervals,
* and CLOCK_MONOTONIC would be preferable for longer-term timers measured in
* minutes, hours or days. Of couse we _are_ measuring short intervals here.
*
* XXX the rest of this is informational -- we really only want CLOCK_MONOTONIC
* here, though CLOCK_PROCESS_CPUTIME_ID would be more accurate on multitasking
* systems.
*
* POSIX.1b-1999 now says there's a CPT option taken from ISO C:
*
* If _POSIX_CPUTIME is defined, implementations shall support clock ID
* values obtained by invoking clock_getcpuclockid(), which represent the
* CPU-time clock of a given process. Implementations shall also support
* the special clockid_t value CLOCK_PROCESS_CPUTIME_ID, which represents
* the CPU-time clock of the calling process when invoking one of the
* clock_*() or timer_*() functions. For these clock IDs, the values
* returned by clock_gettime() and specified by clock_settime() represent
* the amount of execution time of the process associated with the clock.
* Changing the value of a CPU-time clock via clock_settime() shall have
* no effect on the behavior of the sporadic server scheduling policy.
*
* (and similar for CLOCK_THREAD_CPUTIME_ID)
*
* FreeBSD has these, and also has something similar called CLOCK_PROF, which
* presumably accounts for all non-idle (non-wait-io) CPU time.
*
* The Linux manual warns:
*
* The CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks are
* realized on many platforms using timers from the CPUs (TSC on i386,
* AR.ITC on Itanium). These registers may differ between CPUs and as a
* consequence these clocks may return bogus results if a process is
* migrated to another CPU.
*
* If the CPUs in an SMP system have different clock sources then there is
* no way to maintain a correlation between the timer registers since each
* CPU will run at a slightly different frequency. If that is the case
* then clock_getcpuclockid(0) will return ENOENT to signify this
* condition. The two clocks will then only be useful if it can be ensured
* that a process stays on a certain CPU.
*
* The processors in an SMP system do not start all at exactly the same
* time and therefore the timer registers are typically running at an
* offset. Some architectures include code that attempts to limit these
* offsets on bootup. However, the code cannot guarantee to accurately
* tune the offsets. Glibc contains no provisions to deal with these
* offsets (unlike the Linux Kernel). Typically these offsets are small
* and therefore the effects may be negligible in most cases.
*
* The Linux (er, glibc) manual is not clear on whether the CPU TSC registers
* are saved and restored on each context switch either and there are reports
* that at least some kernel versions will count the time spent in sleep(3),
* for example.
*
* Apparently Android made it even worse, according to this comment on StkOvf:
*
* For Android users, using CLOCK_MONOTONIC may be problematic since the
* app may get suspended, along with the clock. For that, Android added
* the ANDROID_ALARM_ELAPSED_REALTIME timer that is accessible through
* ioctl(). [[ Itay Bianco ]]
*
* Darwin/MacOS makes things even worse by repeating the Linux mistakes and then
* also introduces the better performing but less accurate
* CLOCK_MONOTONIC_RAW_APPROX:
*
* like CLOCK_MONOTONIC_RAW, but reads a value cached by the system at
* context switch. This can be read faster, but at a loss of accuracy as
* it may return values that are milliseconds old.
*
* Note that FreeBSD has similar CLOCK_*_FAST, e.g. CLOCK_MONOTONIC_FAST, to
* improve performance but with the limitation of reducing accuracy to "one
* timer tick".
*
* Apparently Linux also fails to adjust CLOCK_MONOTONIC by not necessarily
* incrementing it while the system is asleep (suspended). They apparently
* invented CLOCK_BOOTTIME to work around this sillyness.
*
* Note: suseconds_t is for signed values of times in microseconds, and it was
* first added to POSIX 1003.1 in System Interfaces and Headers, Issue 5
* published in 1997. It must be no greater in size than a long int. Note too
* that POSIX is a bit finicky in specifying that suseconds_t only needs to
* hold integers in the range of [0, 1000000] implicitly limiting it to just
* one second intervals. However we will abuse it slightly and assume it is at
* least 32-bits and so can give us at least 35 second intervals, which should
* be long enough for all our tests?
*
* [1] see also: http://btorpey.github.io/blog/2014/02/18/clock-sources-in-linux/
*/
#ifdef __APPLE__
# define BEST_CLOCK_ID CLOCK_MONOTONIC
# define BEST_CLOCK_ID_NAME __STRING(CLOCK_MONOTONIC)
#endif
#if !defined(BEST_CLOCK_ID)
# if defined(CLOCK_MONOTONIC)
# define BEST_CLOCK_ID CLOCK_MONOTONIC
# define BEST_CLOCK_ID_NAME __STRING(CLOCK_MONOTONIC)
# endif
#endif
/*
* Note in the above: neither ___STRING(), nor __STRING() can work on
* BEST_CLOCK_ID to show the intermediate macro's name -- it's all or nothing
* on expansion of a nested macro definition.
*/
/*
* microtime() - return number of microseconds since some epoch
*
* the particular epoch is irrelevant -- we just use the difference between two
* of these samples taken sufficiently far appart enough that the resolution is
* also relatively unimportant, though better than 1 second is expected....
*/
suseconds_t microtime(void);
static void check_clock_res(void);
#if defined(BEST_CLOCK_ID)
# ifdef __APPLE__
# ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
# if __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
/*
* XXX this is for Darwin / Mac OS X prior to Mac OSX 10.12, which did not
* implement the POSIX (IEEE Std 1003.1b-1993) clock_gettime() API.
*
* macOS 10.12 offers CLOCK_MONOTONIC_RAW with the same claims as Linux, but
* perhaps it is only for Linux compatability and not really necessary.
*
* macOS 10.12 also offers CLOCK_MONOTONIC_RAW_APPROX which is apparently
* implemented using COMMPAGE, so may also be up to milliseconds old.
*
* See also: https://stackoverflow.com/a/21352348/816536
* and: https://developer.apple.com/library/content/qa/qa1398/_index.html
*/
#include <sys/time.h>
#include <sys/resource.h>
#include <mach/mach.h>
#include <mach/clock.h>
#include <mach/mach_time.h>
#include <errno.h>
#include <unistd.h>
#include <sched.h>
typedef enum {
CLOCK_REALTIME,
CLOCK_MONOTONIC,
CLOCK_PROCESS_CPUTIME_ID,
CLOCK_THREAD_CPUTIME_ID
} clockid_t;
static mach_timebase_info_data_t __clock_gettime_inf;
int clock_gettime(clockid_t, struct timespec *);
int
clock_gettime(clockid_t clk_id,
struct timespec *tp)
{
kern_return_t ret;
clock_serv_t clk;
clock_id_t clk_serv_id;
mach_timespec_t tm;
uint64_t start, end, delta, nano;
int retval = -1;
switch (clk_id) {
case CLOCK_REALTIME:
case CLOCK_MONOTONIC:
/* XXX these are both the same! */
/* XXX this is apparently very slow too */
clk_serv_id = clk_id == CLOCK_REALTIME ? REALTIME_CLOCK : SYSTEM_CLOCK;
if ((ret = host_get_clock_service(mach_host_self(), clk_serv_id, &clk)) == KERN_SUCCESS) {
if ((ret = clock_get_time(clk, &tm)) == KERN_SUCCESS) {
tp->tv_sec = tm.tv_sec;
tp->tv_nsec = tm.tv_nsec;
retval = 0;
}
}
if (KERN_SUCCESS != ret) {
errno = EINVAL;
retval = -1;
}
break;
case CLOCK_PROCESS_CPUTIME_ID:
/*
* XXX this is an _extremely_ bad hack, but there you go....
*
* this measures elapsed time in ticks
*/
start = mach_absolute_time();
if (clk_id == CLOCK_PROCESS_CPUTIME_ID) {
getpid();
} else {
sched_yield();
}
end = mach_absolute_time();
delta = end - start;
if (__clock_gettime_inf.denom == 0) {
mach_timebase_info(&__clock_gettime_inf);
}
nano = delta * __clock_gettime_inf.numer / __clock_gettime_inf.denom;
tp->tv_sec = (time_t) (nano * (uint64_t) 1e-9);
tp->tv_nsec = (long) (nano - (uint64_t) (tp->tv_sec * (time_t) 1e9));
retval = 0;
break;
case CLOCK_THREAD_CPUTIME_ID:
default:
errno = EINVAL;
retval = -1;
}
return retval;
}
int clock_getres(clockid_t, struct timespec *);
int
clock_getres(clockid_t clk_id,
struct timespec *tp)
{
kern_return_t ret;
clock_serv_t clk;
clock_id_t clk_serv_id;
natural_t attribute[4];
int retval = -1;
tp->tv_sec = 0;
tp->tv_nsec = 1;
switch (clk_id) {
case CLOCK_REALTIME:
case CLOCK_MONOTONIC:
/* XXX these are both the same! */
clk_serv_id = clk_id == CLOCK_REALTIME ? REALTIME_CLOCK : SYSTEM_CLOCK;
if ((ret = host_get_clock_service(mach_host_self(), clk_serv_id, &clk)) == KERN_SUCCESS) {
mach_msg_type_number_t count;
count = sizeof(attribute)/sizeof(natural_t);
if ((ret = clock_get_attributes(clk, CLOCK_GET_TIME_RES, (clock_attr_t) attribute, &count )) == KERN_SUCCESS) {
tp->tv_sec = 0;
tp->tv_nsec = attribute[0];
retval = 0;
}
}
if (KERN_SUCCESS != ret) {
errno = EINVAL;
retval = -1;
}
break;
case CLOCK_PROCESS_CPUTIME_ID:
if (__clock_gettime_inf.denom == 0) {
mach_timebase_info(&__clock_gettime_inf);
}
tp->tv_sec = 0;
tp->tv_nsec = __clock_gettime_inf.numer / __clock_gettime_inf.denom;
retval = 0;
break;
case CLOCK_THREAD_CPUTIME_ID:
default:
errno = EINVAL;
retval = -1;
}
return retval;
}
# endif
# endif
# endif /* __APPLE__ */
suseconds_t
microtime(void)
{
struct timespec tsnow;
(void) clock_gettime(CLOCK_MONOTONIC, &tsnow);
return (suseconds_t) ((tsnow.tv_sec * 1000000) + (tsnow.tv_nsec / 1000));
}
static void
check_clock_res(void)
{
struct timespec res;
/* XXX "#ifdef CLOCK_PROCESS_CPUTIME_ID"??? */
if (clock_getres(CLOCK_MONOTONIC, &res) == -1) {
err(EXIT_FAILURE, "clock_getres(CLOCK_MONOTONIC)");
}
warnx("using %s timer with resolution: %ld s, %ld ns", BEST_CLOCK_ID_NAME, res.tv_sec, res.tv_nsec);
}
#else /* ! BEST_CLOCK_ID */
/*
* XXX N.B.: apparently on linux times(NULL) is fast and returns a clock_t
* value of CLK_TKS since the epoch, but it is probably implemented using
* gettimeofday() anyway... (note: times() is POSIX-1003.1-1990)
*
* Note that on OS X the gettimeofday() function is implemented in libc as a
* wrapper to either the _commpage_gettimeofday() function, if available, or
* the normal system call. If using the COMMPAGE helper then gettimeofday()
* simply returns the value stored in the COMMPAGE and thus can execute without
* a context switch.
*
* On BSD times() is just implemented using getrusage() and gettimeofday().
*/
suseconds_t
microtime(void)
{
struct timeval tvnow;
(void) gettimeofday(&tvnow, (void *) NULL);
return (suseconds_t) ((tvnow.tv_sec * 1000000) + tvnow.tv_usec);
}
static void
check_clock_res(void)
{
warnx("using gettimeofday() timer with unkown resolution");
return;
}
#endif /* BEST_CLOCK_ID */