Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm making a robot that should have simple two way communication for a large variety of values to a desktop via UART (serial communication, modem port). It's also desirable for it to be easy to add new values.
The board on the robot is an Olimexino, a rather powerful Arduino clone with an arm processor. For the sake of simplicity, I believe it could be affordable to store all relevant global values as floats.
My idea is to store all values in a matrix, like below. On the robot I for instance would like multiple controllers, which here can be viewed just as a heap of values grouped. These should be easy to modify and send.
enum rows
{
controller_a,
controller_b,
controller_c,
rows
}
enum controllers
{
controller_value1,
controller_value2,
columns
}
float values[rows][columns]
This should make it quite easy to for instance add a controller. It would also be rather easy to send and insert values, as I could target any vale by just sending the coordinates as [row, column].
The question is though, are there other better ways?
Should I perhaps define the controllers in structs instead
struct controller
{
float controller_value1;
etc
}controllers[columns];
If I make sure that all controllervalues are floats, maybe I could use pointers to the structs for easy read/write? I dont't know how to do that pointer aritmethics though. I guess it would require a specific routine for handling each different struct, meaning that the code wouldnt be that easy to modify?
First, it is a very very bad idea to use floats if you are going to be sending the data between devices, particularly if they are going to be of different architectures, it would be far more sound to use 64 bit integers and implement a fixed point by hand where necessary. Floats are not of a predictable format in memory and thus trying to serialise them is highly difficult.
Second, I think you have some sound ideas as far as storing the data goes, using a 2D array of a fixed type to store the data will work well and hopefully be well optimised. The enums are also a nice way of avoiding confusion. However what you are missing is a way to send them easily. As you are using a micro a nice simple protocol would do, may I suggest something along the lines of the following. This assumes you are keeping the table synced between your computer and the arduino like:
uint64_t ValueTable[CONTROLLER_MAX][VALUE_MAX];
uint32_t UartFD; // This gets set somewhere during init
// It should be a non blocking fd so we dont block if there are
// no value changes
void SetValue(uint32_t ControllerNum, uint32_t ValueIndex, uint64_t Value)
{
ValueTable[ControllerNum][ValueIndex] = Value;
write(UartFD, &ControllerNum, sizeof(uint32_t));
write(UartFD, &ValueIndex, sizeof(uint32_t));
write(UartFD, &Value, sizeof(uint64_t));
}
void GetValue(void)]
{
uint32_t ContNum;
uint32_t ValIndx;
uint64_t Value;
if(!read(UartFD, &ContNum, sizeof(uint32_t)))
{
// No data waiting
return;
}
// Wait for the rest
while(!read(UartFD, &ValIndx, sizeof(uint32_t)));
while(!read(UartFD, &Value, sizeof(uint64_t)));
ValueTable[ContNum][ValIndx] = Value;
}
Obviously this is the version for the PC, the arduino needs read and write replaced with Serial.read and Serial.write and does not need the first argument, otherwise the two are the same.Obviously you need to call those wherever you write to a value in the table.
Effectively for what you are doing your idea is great, just make sure to keep the implementation fast and simple so it runs well on the robot's embedded system. Yuo need not worry too much about extensibility, as you are likely to update both at once, particularly if you can keep a fair amount of common code between the PC and robot.
Related
My program answers on incoming messages and do some logic based on ID`s and data included in messages.
I have a different function for each ID.
The project is pure C.
To make the code easy to work with I have adjusted all functions to the same style (same return and parameters).
I also want to evade the long switch-case constructions and make code easier to edit later, so I have created the following function:
AnswerStruct IDHandler(Request Message)
{
struct AnswerStruct ANS;
SIDHandler = IDfunctions[Message.ID];
ANS = SIDHandler(Message);
return ANS;
}
AnswerStruct is struct for answer messages.
Request is struct for incoming messages.
IDfunctions is array of pointers to functions which looks like this -
AnswerStruct func1(Request);
AnswerStruct func4(Request);
...
typedef AnswerStruct(*f)(Request);
AnswerStruct (*SIDHandler)(Request);
static f IDfunctions[IDMax] = {0, *func1, 0, 0, *func4, ...};
Function pointers placed in the array cells equal to their id`s, for example:
func1 related to message with ID=1.
func4 related to message with ID=4.
I think, that by using this array I make my life much easier.
I can call function which I need in one step (just go to the IDfunctions[ID]).
Also, adding new functions becomes a two step operation (just add function to the IDfunctions and write logic).
I doubt the efficiency of the selected solution, it seems clunky to me.
The question is - Is this a good architecture?
If no, how can I edit my solution to make it better?
Thanks.
I doubt the efficiency of the selected solution, it seems clunky to
me.
It can be less efficient to call a function via a function pointer than to call it directly by name, because the former denies the compiler any opportunity to optimize the call. But you have to consider whether that actually matters. In a system that dispatches function calls based on messages received from an external source, the I/O involved in receiving the messages is likely to be much more expensive than the indirect function calls, so the difference in call performance is unlikely to be significant.
On the other hand, your approach affords simpler logic and many fewer lines of code, which is a different and potentially more valuable kind of efficiency.
The question is - Is this a good architecture?
The general approach is perfectly good, and I don't see much to complain about in the implementation sketch provided.
Personally, I would declare array IDFunctions to be const (supposing, of course, that you don't intend to replace any of its members after their initialization), but that's a minor safety / performance detail, where again the performance dimension is probably irrelevant.
I am very new to the HM HEVC (and the JEM) reference software, and I am currently trying to understand the source code. I want to add some lines to display for each component: name of Algo (i.e. inter/intra Algos) + length of the bitstream+ position in output bin file.
To know which component cost more bits to code and how codec is working. I want to do same thing for the JEM also after that.
my problem first is that I am unable of understanding a lot of function there, the comment is not sufficient, so is there any references to understand the code??!! (I already read the Manuel ,doesn’t help).
2nd I don’t know where & how exactly to add these lines; is it in TEncGOP, TEncSlice or TEncCU. Ps: I don’t think in TEncGOP.compressGOP so maybe in the 2 other classes.
(I put the answer to comment that #Mourad put four hours ago here, becuase it will be long)
I assume that you could manage to find where the actual encoding after the RDO loop is implemented. As you correctly mentioned, xEncodeCU is the function you need to refer to make sure you are not still in the RDO.
Now you need to find the exact function in xEncodeCU that is responsible for your target codec tool.
For instance, if you want to count the number of bits for coefficient coding, you should be looking into the m_pcEntropyCoder->encodeCoeff() (It's a JEM function and may have different name in the HM). Once you find this line in the xEncodeCU, you may do this and get the number of bits written inside encodeCoeff() function:
UInt b_before = m_pcEntropyCoder->getNumberOfWrittenBits();
m_pcEntropyCoder->encodeCoeff( ... );
UInt b_after = m_pcEntropyCoder->getNumberOfWrittenBits();
UInt writtenBitsCoeff = b_after - b_before;
One important point: as you cas see, the function getNumberOfWrittenBits() gives you integer rates, which is obtained by rounding sum of fractional rates corresponding to all syntax elements coded inside the function encodeCoeff. This error might or might not be acceptable, depending on your problem. For example, if instead of coefficient coding rate, you wanted to know the rate of CBF, then this error would not be acceptable at all. Because, CBF rate is mostly less than one bit. If this is your case, then you would need to calculate the fractional bits one-by-one. It would be totally different and relatively more complicated than this.
Point 1: There is one rule of tumb that logging coding decisions (e.g. pred mode, MV, IPM, block size) is much easier at the decoder side than encoder. This is because of the fact that you have super complicated RDO process at the encoder side that can easily make you get lost in the loops. But at the decoder side, everything appears only once. However, if you insist on doing it at the encoder side, you may find some tips here: Get some information from HEVC reference software
Point 2: Unlike coding decisions, logging rate (i.e. number of written bits for different syntax elements) is more complicated at the decoder side than encoder. This is particularly true for fractional bits associated to anything that is encoded in non-EP mode (i.e. with CABAC contexts). So you may do this part at the ecoder side. But I am afraid it is not easy.
Point 3: I think the best way to understand the code is to read it line-by-line. It's very time-consuming but if you theoritically know the standard(s), you will probably be able to distiguish important parts and ignore the rest.
PS: I think there are too many questions, mostly too general, in your post. It makes it a bit difficult for me to answer them all together. So you I'll wait for you to take your next step and ask more precise questions.
In an implementation of the Game of Life, I need to handle user events, perform some regular (as in periodic) processing and draw to a 2D canvas. The details are not particularly important. Suffice it to say that I need to keep track of a large(-ish) number of variables. These are things like: a structure representing the state of the system (live cells), pointers to structures provided by the graphics library, current zoom level, coordinates of the origin and I am sure a few others.
In the main function, there is a game loop like this:
// Setup stuff
while (!finished) {
while (get_event(&e) != 0) {
if (e.type == KEYBOARD_EVENT) {
switch (e.key.keysym) {
case q:
case x:
// More branching and nesting follows
The maximum level of nesting at the moment is 5. It quickly becomes unmanageable and difficult to read, especially on a small screen. The solution then is to split this up into multiple functions. Something like:
while (!finished {
while (get_event(&e) !=0) {
handle_event(state, origin_x, origin_y, &canvas, e...) //More parameters
This is the crux of the question. The subroutine must necessarily have access to the state (represented by the origin, the canvas, the live cells etc.) in order to function. Passing them all explicitly is error prone (which order does the subroutine expect them in) and can also be difficult to read. Aside from that, having functions with potentially 10+ arguments strikes me as a symptom of other design flaws. However the alternatives that I can think of, don't seem any better.
To summarise:
Accept deep nesting in the game loop.
Define functions with very many arguments.
Collate (somewhat) related arguments into structs - This really only hides the problem, especially since the arguments are only loosely related.
Define variables that represent the application state with file scope (static int origin_x; for example). If it weren't for the fact that it has been drummed into me that global variable are usually a terrible idea, this would be my preferred option. But if I want to display two views of the same instance of the Game of Life in the future, then the file scope no longer looks so appealing.
The question also applies in slightly more general terms I suppose: How do you pass state around a complicated program safely and in a readable way?
EDIT:
My motivations here are not speed or efficiency or performance or anything like this. If the code takes 20% longer to run as a result of the choice made here that's just fine. I'm primarily interested in what is less likely to confuse me and cause the least headache in 6 months time.
I would consider the canvas as one variable, containing a large 2D array...
consider static allocation
bool canvas[ROWS][COLS];
or dynamic
bool *canvas = malloc(N*M*sizeof(int));
In both cases you can refer to the cell at position i,j as canvas[i][j]
though for dynamic allocation, do not forget to free(canvas) at the end. You can then use a nested loop to update your state.
Search for allocating/handling a 2d array in C and examples or tutorials... Possibly check something like this or similar? Possibly this? https://www.geeksforgeeks.org/nested-loops-in-c-with-examples/
Also consider this Fastest way to zero out a 2d array in C?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So pointers are something a lot of people (including myself) get a little confused on. I understand how they work, but when im making an application or whatever....how do I know when it would be best to use them?
Is there like a general rule/guideline of when it's actually a good idea to use them. I feel like I understand their concept for the most part, but always struggle in wondering if I should be using a pointer here or there etc...
Thank you.
They are a basic part of the C language. Without being rude, I think the key thing to consider is that they are not something to be avoided. They are another tool at your disposal, and a powerful one at that.
In general, they are used when you want to access large amounts of data (ie: arrays, massive structures, dynamic memory allocation, etc). They are also very useful when designing APIs (application programming interfaces). This shouldn't really be C# question, as in C# and C++, you can pass by value or by reference, and the nature of your question changes based on the usefulness of passing by value or reference, along with the user of other means of accessing data external to a function, class, etc.
Pass by Reference / Value in C++
If you can just pass by value, and the value is read-only, you're fine without a pointer, as you have no means to change the value. A common case is a simple sum function:
int sum (int a, int b) {
int value = a + b;
return value;
}
You have no need to modify the values provided, and you're only accessing simple values, rather than arrays or complex structures.
Now, if you're modifying the contents of a large array, especially if the size of the array can change at run time (ie: linked lists and other data structures) you need pointers, period. If you're modifying multiple values, you could either use pointers, or you could just use the return value of a function (ie: int mysum = sum(1,2);). About the only concern I encounter when using pointers in regular work is making sure any possible NULL pointer values are checked for at the beginning of each function. The real problem is when working with larger projects where you can get non-NULL, invalid/corrupt pointers from a poorly written third party API or library. That's where the real fun begins, debugging with JTAG debuggers, GDB, etc.
For c, I think you will naturally end up using pointers for just about any but the most trivial of trivial programs. You will need a pointer when you want to refer to any non-basic type, e.g. structs, arrays (including strings).
Lots of other places too:
any time you do dynamic memory allocation (malloc() and friends)
if you need to return more than one "thing" from a function, you can pass a pointer to the storage for that object and have the function populate that memory
you might need to use function pointers
probably lots of other examples too.
Well, a couple of easy-bits would be, in case of dynamic memory allocation, you would want to use Pointers.
If you are not sure of the size of arrays that you are going to use, better implement a linked list.
Want multiple return values from a function, better pass the address of variables to be modified.
Any place, where you are not 100% sure, if you should be using a normal variable, use Pointer.
Important: Please see this very much related question: Return multiple values in C++.
I'm after how to do the same thing in ANSI C? Would you use a struct or pass the addresses of the params in the function? I'm after extremely efficient (fast) code (time and space), even at the cost of readability.
EDIT: Thanks for all the answers. Ok, I think I owe some explanation: I'm writing this book about a certain subset of algorithms for a particular domain. I have set myself the quite arbitrary goal of making the most efficient (time and space) implementations for all my algos to put up on the web, at the cost of readability and other stuff. That is in part the nature of my (general) question.
Answer: I hope I get this straight, from (possibly) fastest to more common-sensical (all of this a priori, i.e. without testing):
Store outvalues in global object (I would assume something like outvals[2]?), or
Pass outvalues as params in the function (foo(int in, int *out1, int *out2)), or
return a struct with both outvals, or
(3) only if the values are semantically related.
Does this make sense? If so, I think Jason's response is the closest, even though they all provide some piece of the "puzzle". Robert's is fine, but at this time semantics is not what I'm after (although his advice is duly noted).
Both ways are valid, certianly, but I would would consider the semantics (struct vs parameter reference) to decide which way best communicates you intentions to the programmer.
If the values you are returning are tightly coupled, then it is okay to return them as a structure. But, if you are simply creating artificial mechanism to return values together (as a struct), then you should use a parameter reference (i.e. pass the address of the variables) to return the values back to the calling function.
As Neil says, you need to judge it for yourself.
To avoid the cost of passing anything, use a global. Next best is a single structure passed by pointer/reference. After that are individual pointer/reference params.
However, if you have to pack data into the structure and then read it back out after the call, you may be better off passing individual parameters.
If you're not sure, just write a bit of quick test code using both approaches, execute each a few hundred thousand times, and time them to see which is best.
You have described the two possible solutions and your perceived performance constraint. Where you go from here is really up to you - we don't have enough information to make an informed judgement.
Easiest to read should be passed addresses in the function, and it should be fast also, pops and pushes are cheap:
void somefunction (int inval1, int inval2, int *outval1, int *outval2) {
int x = inval1;
int y = inval2;
// do some processing
*outval1 = x;
*outval2 = y;
return;
}
The fastest Q&D way that I can think of is to pass the values on a global object, this way you skip the stack operation just keep in mind that it won't be thread safe.
I think that when you return a struct pointer, you probably need to manually find some memory for that. Addresses in parameter list are allocated on the stack, which is way faster.
Keep in mind that sometimes is faster to pass parameters by value and update on return (or make local copies on the stack) than by reference... This is very evident with small structures or few parameters and lots of accesses.
This depends massively on your architecture, and also if you expect (or can have) the function inlined. I'd first write the code in the simplest way, and then worry about speed if that shows up as an expensive part of your code.
I would pass the address to a struct. If the information to be returned isn't complex, then just passing in the addresses to the values would work too.
Personally, it really comes down to how messy the interface would be.
void SomeFunction( ReturnStruct* myReturnVals )
{
// Fill in the values
}
// Do some stuff
ReturnStruct returnVals;
SomeFunction( &returnVals);
// Do more stuff
In either case, you're passing references, so performance should be similar. If there is a chance that the function never actually returns a value, you could avoid the cost of the malloc with the "return a struct" option since you'd simply return null.
My personal preference is to return a dynamically allocated (malloc'd) struct. I avoid using function arguments for output because I think it makes code more confusing and less maintainable in the long-term.
Returning a local copy of the structure is bad because if the struct was declared as non-static inside the function, it becomes null and void once you exit the function.
And to all the folks suggesting references, well the OP did say "C," and C doesn't have them (references).
And sweet feathery Jesus, can I wake up tomorrow and not have to see anything about the King of Flop on TV?