1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . IO ;
4+ using System . Linq ;
5+ using System . Text ;
6+ using BenchmarkDotNet . Attributes ;
7+ using InfluxDB . LineProtocol ;
8+ using InfluxDB . LineProtocol . Payload ;
9+
10+ namespace Benchmark
11+ {
12+ [ MemoryDiagnoser ]
13+ public class WriteLineProtocol
14+ {
15+ private const int N = 500 ;
16+
17+ private static readonly string [ ] Colours = { "red" , "blue" , "green" } ;
18+
19+ private readonly ( DateTime timestamp , string colour , double value ) [ ] data ;
20+
21+ public WriteLineProtocol ( )
22+ {
23+ var random = new Random ( 755 ) ;
24+ var now = DateTime . UtcNow ;
25+ data = Enumerable . Range ( 0 , N ) . Select ( i => ( now . AddMilliseconds ( random . Next ( 2000 ) ) , Colours [ random . Next ( Colours . Length ) ] , random . NextDouble ( ) ) ) . ToArray ( ) ;
26+ }
27+
28+ [ Benchmark ( Baseline = true ) ]
29+ public string LineProtocolPoint ( )
30+ {
31+ var payload = new LineProtocolPayload ( ) ;
32+
33+ foreach ( var point in data )
34+ {
35+ payload . Add ( new LineProtocolPoint (
36+ "example" ,
37+ new Dictionary < string , object >
38+ {
39+ { "value" , point . value }
40+ } ,
41+ new Dictionary < string , string >
42+ {
43+ { "colour" , point . colour }
44+ } ,
45+ point . timestamp
46+ ) ) ;
47+ }
48+
49+ var writer = new StringWriter ( ) ;
50+ payload . Format ( writer ) ;
51+ return writer . ToString ( ) ;
52+ }
53+
54+ [ Benchmark ]
55+ public string LineProtocolWriter ( )
56+ {
57+ var writer = new LineProtocolWriter ( ) ;
58+
59+ foreach ( var point in data )
60+ {
61+ writer . Measurement ( "example" ) . Tag ( "colour" , point . colour ) . Field ( "value" , point . value ) . Timestamp ( point . timestamp ) ;
62+ }
63+
64+ return writer . ToString ( ) ;
65+ }
66+
67+ [ Benchmark ]
68+ public string StringInterpolation ( )
69+ {
70+ var unixEpoch = new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 , DateTimeKind . Utc ) ;
71+
72+ var lines = new List < string > ( ) ;
73+
74+ foreach ( var point in data )
75+ {
76+ var timestamp = point . timestamp - unixEpoch ;
77+ lines . Add ( $ "example,colour={ point . colour } value={ point . value } { timestamp . Ticks * 100L } ") ;
78+ }
79+
80+ return string . Join ( "\n " , lines ) ;
81+ }
82+
83+ [ Benchmark ]
84+ public string StringBuilder ( )
85+ {
86+ var unixEpoch = new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 , DateTimeKind . Utc ) ;
87+
88+ var lines = new StringBuilder ( ) ;
89+
90+ foreach ( var point in data )
91+ {
92+ var timestamp = point . timestamp - unixEpoch ;
93+ lines . Append ( "example,colour=" ) . Append ( point . colour ) . Append ( " value=" ) . Append ( point . value ) . Append ( " " ) . Append ( timestamp . Ticks * 100L ) . Append ( "\n " ) ;
94+ }
95+
96+ return lines . ToString ( ) ;
97+ }
98+ }
99+ }
0 commit comments