first commit

This commit is contained in:
gxt_kt 2024-12-04 19:35:03 +08:00
commit 573b3e7a23
8 changed files with 483 additions and 0 deletions

308
.clang-format Normal file
View File

@ -0,0 +1,308 @@
---
Language: Cpp
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Left
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Never
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: Yes
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 2
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: false
AtStartOfFile: true
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: NextLine
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
PPIndentWidth: -1
QualifierAlignment: Leave
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
- ParseTestProto
- ParsePartialTestProto
CanonicalDelimiter: pb
BasedOnStyle: google
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Auto
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
...

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
build/
cmake-build*
.cache
.idea
.vscode
.cache
*__pycache__*
*.md-E
*.log

65
CMakeLists.txt Normal file
View File

@ -0,0 +1,65 @@
cmake_minimum_required(VERSION 3.0)
project(cmake_template)
include(cmake/help.cmake)
set(CMAKE_BUILD_TYPE Release) # Debug Release RelWithDebInfo
# set a debug postfix
set(CMAKE_DEBUG_POSTFIX "-dbg")
# set(CMAKE_C_COMPILER "gcc") # gcc clang
# set(CMAKE_CXX_COMPILER "g++") # g++ clang++
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# set the most strict compile rule
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
add_compile_options(-Wall)
# add_compile_options(-Wall -Wextra -Wpedantic -Werror)
elseif(CMAKE_C_COMPILER_ID STREQUAL "MSVC")
add_compile_options(/W4 /WX)
endif()
include_directories(include)
if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
message("Building for Linux platform")
elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin")
message("Building for macOS platform")
elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
message("Building for Windows platform")
else()
message(FATAL_ERROR "Unsupported platform: ${CMAKE_SYSTEM_NAME}")
endif()
option(OPTION_TEST "whether or not to build the tests" ON)
if(OPTION_TEST)
PrintVariable(OPTION_TEST)
endif()
# add_definitions(-DMY_MACRO)
# target_compile_definitions(demo PRIVATE MY_MACRO)
# add_library(demo SHARED ${detail_header} ${header} ${src})
# target_include_directories(demo)
# target_compile_definitions(demo PUBLIC COMPILE_TEST=)
find_package(debugstream)
find_package(Boost REQUIRED)
# find_package(ZeroMQ_INCLUDE_DIR)
include_directories(include)
add_executable(send src/send.cc)
target_link_libraries (send ${Boost_LIBRARIES}) #boost
target_link_libraries(send debugstream)
add_executable(receive src/receive.cc)
target_link_libraries (receive ${Boost_LIBRARIES}) #boost
target_link_libraries(receive debugstream)
# target_link_libraries(demo ZeroMQ_LIBRARY)

11
README.md Normal file
View File

@ -0,0 +1,11 @@
# boost asio test
test time interval between send and receive
```c++
cmake -S . -B build
cmake --build build -j
./build/receive
./build/send
```

4
cmake/help.cmake Normal file
View File

@ -0,0 +1,4 @@
# print value
macro(PrintVariable var_name)
message(STATUS "${var_name}=${${var_name}}")
endmacro()

0
include/common.h Normal file
View File

44
src/receive.cc Normal file
View File

@ -0,0 +1,44 @@
#include <boost/asio.hpp>
#include <chrono>
#include <iostream>
#include <string>
int main() {
try {
boost::asio::io_context io_context;
// 创建 UDP socket
boost::asio::ip::udp::socket socket(
io_context,
boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345));
while (true) {
char recv_buffer[1024];
boost::asio::ip::udp::endpoint sender_endpoint;
// 接收数据
size_t len = socket.receive_from(boost::asio::buffer(recv_buffer),
sender_endpoint);
std::string received_message(recv_buffer, len);
// 解码时间字符串为微秒
long long received_time_us = std::stoll(received_message);
auto now = std::chrono::high_resolution_clock::now();
auto current_time_us =
std::chrono::duration_cast<std::chrono::microseconds>(
now.time_since_epoch())
.count();
// 计算时间差
long long time_difference = current_time_us - received_time_us;
std::cout << "Received: " << received_message
<< " | Time difference: " << time_difference << " us"
<< std::endl;
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}

42
src/send.cc Normal file
View File

@ -0,0 +1,42 @@
#include <boost/asio.hpp>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
int main() {
try {
boost::asio::io_context io_context;
// 创建 UDP socket
boost::asio::ip::udp::socket socket(io_context);
socket.open(boost::asio::ip::udp::v4());
// 设置目标地址和端口
boost::asio::ip::udp::endpoint receiver_endpoint(
boost::asio::ip::make_address("127.0.0.1"), 12345);
while (true) {
// 获取当前时间,转换为微秒
auto now = std::chrono::high_resolution_clock::now();
auto duration = now.time_since_epoch();
auto microseconds =
std::chrono::duration_cast<std::chrono::microseconds>(duration)
.count();
// 转换为字符串
std::string message = std::to_string(microseconds);
// 发送数据
socket.send_to(boost::asio::buffer(message), receiver_endpoint);
std::cout << "Sent: " << message << std::endl;
// 等待 50 毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}