I am new in stackoverflow and i am sorry if i make mistakes.
I am starter in C language and i have one project what it needs to subtact a weight per second.For example
Weight: 50kg
Subtract per second 4%
i found this code
while(waitFor(1))
{
*weight=(*weight)-(*weight)*0.4;
}
void waitFor(int secs)
{
int retTime;
retTime = time(0) + secs; // Get finishing time.
while (time(0) < retTime); // Loop until it arrives.
}
But i dont want to wait x seconds to finish. I want faster solution. Any ideas
**Note: I want to know how much seconds need to make weight 0
Sleep command it is not working in my computer.
**
For cleaning and disinfecting of the pool dropped into the water of a chemical
a solid body. This solid body upon contact with water
immediately begins to dissolve, losing weight equal to 4% by mass per second.
If the dissolution rate of the chemical remains constant, to implement program
will accept the weight of the solid body in grams and displays after how
time will completely dissolve. The time is displayed in a "hours: minutes: seconds".
For example, if the dissolution time is 3,740 seconds, displaying 01: 02: 20.
To calculate the time you need to implement a function which accepts
gram and return the three time parameters ie
hours, minutes and seconds. Note that the time printed on the main
function.
you can use sleep(int) function in loop it will wait suspend the process up to the integer value.
while((1) && weight > 0)
{
sleep(1);
*weight=(*weight)-(*weight)*0.4;
}
it will wait for 1 seconds and subtraction will made, it will run continuously
Edit:
To find out the number of seconds required for the weight to reach 0:
unsigned seconds = 0;
while(*weight != 0){
*weight -= *weight * 0.04
seconds++;
//in case you have the patience to attend:
sleep(1000); //in milliseconds => 1 second
}
Please note that weight is considered to be a pointer to an integer type.
Related
I am wanting to create a program using a for-loop that slowly increases the brightness of an LED as "start-up" when I press a button.
I have basically no knowledge of for loops. I've tried messing around by looking at similar programs and potential solutions, but I was unable to do it.
This is my start code, which I have to use PWMperiod to achieve.
if (SW3 == 0) {
for (unsigned char PWMperiod = 255; PWMperiod != 0; PWMperiod --) {
if (TonLED4 == PWMperiod) {
TonLED4 += 1;
}
__delay_us (20);
}
}
How would I start this/do it?
For pulse width modulation, you'd want to turn the LED off for a certain amount of time, then turn the LED on for a certain amount of time; where the amounts of time depend on how bright you want the LED to appear and the total period ("on time + off time") is constant.
In other words, you want a relationship like period = on_time + off_time where period is constant.
You also want the LED to increase brightness slowly. E.g. maybe go from off to max. brightness over 10 seconds. This means you'll need to loop total_time / period times.
How bright the LED should be, and therefore how long the on_time should be, will depend on how much time has passed since the start of the 10 seconds (e.g. 0 microseconds at the start of the 10 seconds and period microseconds at the end of the 10 seconds). Once you know the on_time you can calculate off_time by rearranging that "period = on_time + off_time" formula.
In C it might end up something like:
#define TOTAL_TIME 10000000 // 10 seconds, in microseconds
#define PERIOD 1000 // 1 millisecond, in microseconds
#define LOOP_COUNT (TOTAL_TIME / PERIOD)
int on_time;
int off_time;
for(int t = 0; t < LOOP_COUNT; t++) {
on_time = period * t / LOOP_COUNT;
off_time = period - on_time;
turn_LED_off();
__delay_us(off_time);
turn_LED_on();
__delay_us(on_time);
}
Note: on_time = period * t / LOOP_COUNT; is a little tricky. You can think it as on_time = period * (t / LOOP_COUNT); where t / LOOP_COUNT is a fraction that goes from 0.00000 to 0.999999 representing the fraction of the period that the LED should be turned on, but if you wrote it like that the compiler will truncate the result of t / LOOP_COUNT to an integer (round it towards zero) so the result will be zero. When written like this; C will do the multiplication first, so it'll behave like on_time = (period * t) / LOOP_COUNT; and truncation (or rounding) won't be a problem. Sadly, doing the multiplication first solves one problem while possibly causing another problem - period * t might be too big for an int and might cause an overflow (especially on small embedded systems where an int could be 16 bits). You'll have to figure out how big an int is for your computer (for the values you use - changing TOTAL_TIME or PERIOD with change the maximum value that period * t could be) and use something larger (e.g. a long maybe) if an int isn't enough.
You should also be aware that the timing won't be exact, because it ignores time spent executing your code and ignores anything else the OS might be doing (IRQs, other programs using the CPU); so the "10 seconds" might actually be 10.5 seconds (or worse). To fix that you need something more complex than a __delay_us() function (e.g. some kind of __delay_until(absolute_time) maybe).
Also; you might find that the LED doesn't increase brightness linearly (e.g. it might slowly go from off to dull in 8 seconds then go from dull to max. brightness in 2 seconds). If that happens; you might need a lookup table and/or more complex maths to correct it.
I'm making simple game and trying to make char spawn after 5 sec from the start of the game. This is part of my code and I not sure if I have to use time.h or loop function or something. Can anyone give me some advice? Thank you
char * image =
/**/ "H H"
/**/ "H H"
/**/ "HHHHH"
/**/ "H H"
/**/ "H H";
#define HERO_WIDTH (5)
#define HERO_HEIGHT (5)
void setup_hero( void ) {
// Set up the hero at the centre of the screen.
int hero_x = ( screen_width() - HERO_WIDTH ) / 2;
int hero_y = ( screen_height() - HERO_HEIGHT ) / 2;
hero = sprite_create( hero_x, hero_y, HERO_WIDTH, HERO_HEIGHT, image );
wait(5); // not working
sprite_draw(image);
show_screen();
}
Normally, games are event-oriented. They have a main loop that pretty much does nothing but poll the user input, update a timer, and update/render all the entities in the scene.
The timer updated by the main loop keeps track of the number of milliseconds passed since the last iteration of the loop, and is often called the 'delta' time. Delta time is extremely useful for scaling the speed of animation and sound, because the amount of time it takes for the main loop to complete varies depending on a large number of factors.
One way to accomplish what you're trying to do give your entity a counter set to 0 when it's first spawned. Every time the entity is updated, add the delta time to the counter. When the counter is greater than or equal to 5000ms, then 5 seconds have passed.
The best way to implement delta time in C is to use the clock function in <time.h>. It returns the number of cpu cycles that have passed since the program was started. Dividing this value by CLOCKS_PER_SEC / 1000 will give you the number of milliseconds that have passed. subtract the time for the last iteration from the current time to get the delta time.
see: http://www.tutorialspoint.com/c_standard_library/c_function_clock.htm
I am a bit confused about how to write the code to implement this concept. So please help me out if anyone knows how to work around my problem.
I have a while loop to run a simulation where I want to see the diffusion of a mass of fluid for a time that is given by t_domain. The time t is incremented in steps of dt both of which are variables of the type double, however I want to take snapshots of the diffusion process only at Del_t time intervals. What I mean is that if I run my simulation for 1000 seconds where time t is incremented by 0.01 seconds, I want to take the snapshots of the diffusion process every 10 seconds.
Now what I am unable to figure out is the section of the code for the print densities at every nth time step to a file. Can someone give suggestions?
while(t<t_domain)
{
//runs a function to solve the continuity equation and Navier Stokes equation
density_solve(fdparam_1.N,r,r0,ux0,vy0,fdparam_1.Dt,fdparam_1.diff,fdparam_1.MAXIT);
//print densities at every nth time step to a file
t+=dt
}
Thanks in advance
int i = 0;
int times = 23;
while(t<t_domain)
{
//runs a function to solve the continuity equation and Navier Stokes equation
density_solve(fdparam_1.N,r,r0,ux0,vy0,fdparam_1.Dt,fdparam_1.diff,fdparam_1.MAXIT);
//print densities at every nth time step to a file
if(i++%times==0)
{
// print every 23th loop round
}
t+=dt
}
Write a if statement to check like this :
while(t<t_domain)
{
//runs a function to solve the continuity equation and Navier Stokes equation
density_solve(fdparam_1.N,r,r0,ux0,vy0,fdparam_1.Dt,fdparam_1.diff,fdparam_1.MAXIT);
if(((int)t*100)%1000==0)
{
//print densities at every nth time step to a file
}
t+=dt
}
now every time t is 10's multiple it is printed.
As your time would come in float or double with precision of 0.01 I multiply time by 100 to convert it to a workable integer.now I check if it is divisible by 100*10 i.e, 1000 to check if it is a perfect multiple of 10.To make the long story short.........
only numbers like 10.00 and 20.00 are accepted and not
numbers like 10.01 or 10.79
int iteration = 0;
const int N = 10;
while(t<t_domain)
{
...
if(0 == (iteration++ % N))
{
// will printe once every 10 iterations
printf(...);
}
}
My CPU has four cores,MAC os. I use 4 threads to calculate an array. But the time of calculating does't being reduced. If I don't use multithread, the time of calculating is about 52 seconds. But even I use 4 multithreads, or 2 threads, the time doesn't change.
(I know why this happen now. The problem is that I use clock() to calculate the time. It is wrong when it is used in multithread program because this function will multiple the real time based on the num of threads. When I use time() to calculate the time, the result is correct.)
The output of using 2 threads:
id 1 use time = 43 sec to finish
id 0 use time = 51 sec to finish
time for round 1 = 51 sec
id 1 use time = 44 sec to finish
id 0 use time = 52 sec to finish
time for round 2 = 52 sec
id 1 and id 0 is thread 1 and thread 0. time for round is the time of finishing two threads. If I don't use multithread, time for round is also about 52 seconds.
This is the part of calling 4 threads:
for(i=1;i<=round;i++)
{
time_round_start=clock();
for(j=0;j<THREAD_NUM;j++)
{
cal_arg[j].roundth=i;
pthread_create(&thread_t_id[j], NULL, Multi_Calculate, &cal_arg[j]);
}
for(j=0;j<THREAD_NUM;j++)
{
pthread_join(thread_t_id[j], NULL);
}
time_round_end=clock();
int round_time=(int)((time_round_end-time_round_start)/CLOCKS_PER_SEC);
printf("time for round %d = %d sec\n",i,round_time);
}
This is the code inside the thread function:
void *Multi_Calculate(void *arg)
{
struct multi_cal_data cal=*((struct multi_cal_data *)arg);
int p_id=cal.thread_id;
int i=0;
int root_level=0;
int leaf_addr=0;
int neighbor_root_level=0;
int neighbor_leaf_addr=0;
Neighbor *locate_neighbor=(Neighbor *)malloc(sizeof(Neighbor));
printf("id:%d, start:%d end:%d,round:%d\n",p_id,cal.start_num,cal.end_num,cal.roundth);
for(i=cal.start_num;i<=cal.end_num;i++)
{
root_level=i/NUM_OF_EACH_LEVEL;
leaf_addr=i%NUM_OF_EACH_LEVEL;
if(root_addr[root_level][leaf_addr].node_value!=i)
{
//ignore, because this is a gap, no this node
}
else
{
int k=0;
locate_neighbor=root_addr[root_level][leaf_addr].head;
double tmp_credit=0;
for(k=0;k<root_addr[root_level][leaf_addr].degree;k++)
{
neighbor_root_level=locate_neighbor->neighbor_value/NUM_OF_EACH_LEVEL;
neighbor_leaf_addr=locate_neighbor->neighbor_value%NUM_OF_EACH_LEVEL;
tmp_credit += root_addr[neighbor_root_level][neighbor_leaf_addr].g_credit[cal.roundth-1]/root_addr[neighbor_root_level][neighbor_leaf_addr].degree;
locate_neighbor=locate_neighbor->next;
}
root_addr[root_level][leaf_addr].g_credit[cal.roundth]=tmp_credit;
}
}
return 0;
}
The array is very large, each thread calculate part of the array.
Is there something wrong with my code?
It could be a bug, but if you feel the code is correct, then the overhead of parallelization, mutexes and such, might mean the overall performance (runtime) is the same as for the non-parallelized code, for the size of elements to compute against.
It might be an interesting study, to do looped code, single-threaded, and the threaded code, against very large arrays (100k elements?), and see if the results start to diverge to be faster in the parallel/threaded code?
Amdahl's law, also known as Amdahl's argument,[1] is used to find the maximum expected improvement to an overall system when only part of the system is improved. It is often used in parallel computing to predict the theoretical maximum speedup using multiple processors.
https://en.wikipedia.org/wiki/Amdahl%27s_law
You don't always gain speed by multi-threading a program. There is a certain amount of overhead that comes with threading. Unless there is enough inefficiencies in the non-threaded code to make up for the overhead, you'll not see an improvement. A lot can be learned about how multi-threading works even if the program you write ends up running slower.
I know why this happen now. The problem is that I use clock() to calculate the time. It is wrong when it is used in multithread program because this function will multiple the real time based on the num of threads. When I use time() to calculate the time, the result is correct.
I have a buffer with the UTC time stamp in C, I broadcast that buffer after every ten seconds. The problem is that the time difference between two packets is not consistent. After 5 to 10 iterations the time difference becomes 9, 11 and then again 10. Kindly help me to sort out this problem.
I am using <time.h> for UTC time.
If your time stamp has only 1 second resolution then there will always be +/- 1 uncertainty in the least significant digit (i.e. +/- 1 second in this case).
Clarification: if you only have a resolution of 1 second then your time values are quantized. The real time, t, represented by such a quantized value has a range of t..t+0.9999. If you take the difference of two such times, t0 and t1, then the maximum error in t1-t0 is -0.999..+0.999, which when quantized is +/-1 second. So in your case you would expect to see difference values in the range 9..11 seconds.
A thread that sleeps for X milliseconds is not guaranteed to sleep for precisely that many milliseconds. I am assuming that you have a statement that goes something like:
while(1) {
...
sleep(10); // Sleep for 10 seconds.
// fetch timestamp and send
}
You will get a more accurate gauge of time if you sleep for shorter periods (say 20 milliseconds) in a loop checking until the time has expired. When you sleep for 10 seconds, your thread gets moved further out of the immediate scheduling priority of the underlying OS.
You might also take into account that the time taken to send the timestamps may vary, depending on network conditions, etc, if you do a sleep(10) -> send ->sleep(10) type of loop, the time taken to send will be added onto the next sleep(10) in real terms.
Try something like this (forgive me, my C is a little rusty):
bool expired = false;
double last, current;
double t1, t2;
double difference = 0;
while(1) {
...
last = (double)clock();
while(!expired) {
usleep(200); // sleep for 20 milliseconds
current = (double)clock();
if(((current - last) / (double)CLOCKS_PER_SEC) >= (10.0 - difference))
expired = true;
}
t1 = (double)clock();
// Set and send the timestamp.
t2 = (double)clock();
//
// Calculate how long it took to send the stamps.
// and take that away from the next sleep cycle.
//
difference = (t2 - t1) / (double)CLOCKS_PER_SEC;
expired = false;
}
If you are not bothered about using the standard C library, you could look at using the high resolution timer functionality of windows such as QueryPerformanceFrequency/QueryPerformanceCounter functions.
LONG_INTEGER freq;
LONG_INTEGER t2, t1;
//
// Get the resolution of the timer.
//
QueryPerformanceFrequency(&freq);
// Start Task.
QueryPerformanceCounter(&t1);
... Do something ....
QueryPerformanceCounter(&t2);
// Very accurate duration in seconds.
double duration = (double)(t2.QuadPart - t1.QuadPart) / (double)freq.QuadPart;