Printing output at every nth time step - c

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(...);
}
}

Related

Spawning after time passed in C

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

Applying easing to a loop delay

To speak simple, I am trying to figure out how to apply easing to a loop delay.
for (i := 0; i < 114; i++) {
// do a task
time.Sleep(//delay before next job)
}
As you can read it, this is very basic. Let say I want to complete the whole loop in 3s (job completion time is negligeable, t <= us). What is the proper method with Penner's Equations to calculate for each iteration the proper eased delay ?
So, with this function, to simulate an acceleration from zero-velocity, how should I use the t parameter each iteration of the loop to create the proper delay to sleep for ?
func easeInQuad(t float64) {
return math.Pow(t, 2)
}
I would be very thankfull if you could help me about this. Equations has not been a problem so far, but how to use them with my use case instead.
My question could looks like this one at first : Applying easing to setTimeout delays, within a loop
but this one does not take the total time of the loop in account.
However, I think it may be better to use equations rewritten to use only one parameter, in range [0,1] : https://gist.github.com/rezoner/713615dabedb59a15470
From my understanding, I have to calculate the abstract "percentage time elapsed", and somehow interpolate this value with an easing function.
This Node project seems to do just that : https://github.com/CharlotteGore/animation-timer, but again I can't figure out how to reproduce it.
Penner's Equations fundamentally require two parameters: the current progress, and the total possible progress. Alternatively, however, you can instead provide it with percentage-of-total-progress as a single parameter (as a value between 0 and 1), since that's what it uses the current and total to calculate anyway.
Using your original code, if you want 114 iterations to take place within 3 seconds, the easiest way is to use your iteration index as the current progress, and 114 as the total, then multiply the calculated delay factor by your total duration 3.0s.
Note, Penner's Equations calculate total displacement from start position, NOT relative displacement for each step, so you actually need to calculate that difference yourself. Thus the delay for this iteration is the total displacement (delay) for this iteration minus the total displacement for the last iteration:
func DoStuffWithEasing() {
iterations := 114
runTime := 3 * time.Second
for i := 1; i <= iterations; i++ {
// do a task
time.Sleep(easeInQuadDelay(i, iterations, runTime))
}
}
func easeInQuadDelay(c, t int, dur time.Duration) time.Duration {
if c <= 0 || t == 0 { // invalid cases
return 0
}
// This return can be a single-liner, but I split it up for clarity
// Note that time.Durations are fundamentally int64s,
// so we can easily type convert them to float64s and back
this := math.Pow(float64(c)/float64(t), 2)
last := math.Pow(float64(c-1)/float64(t), 2)
return time.Duration((this - last) * float64(dur))
}
https://play.golang.org/p/TTgZUYUvxW
Graph of the easing
I think, you can use time.Ticker.
numLoops := 144
timePerIteration := time.Duration(3) * time.Second / time.Duration(numLoops)
ticker := time.NewTicker(timePerIteration)
for i := 0; i < numLoops; i++ {
// your code
<-ticker.C
}
ticker.Stop()

Using multithreads to calculate data but it does't reduce the time

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.

How do I create a "twirly" in a C program task?

Hey guys I have created a program in C that tests all numbers between 1 and 10000 to check if they are perfect using a function that determines whether a number is perfect. Once it finds these it prints them to the user, they are 6, 28, 496 and 8128. After this the program then prints out all the factors of each perfect number to the user. This is all fine. Here is my problem.
The final part of my task asks me to:
"Use a "twirly" to indicate that your program is happily working away. A "twirly" is the following characters printed over the top of each other in the following order: '|' '/' '-' '\'. This has the effect of producing a spinning wheel - ie a "twirly". Hint: to do this you can use \r (instead of \n) in printf to give a carriage return only (instead of a carriage return linefeed). (Note: this may not work on some systems - you do not have to do it this way.)"
I have no idea what a twirly is or how to implement one. My tutor said it has something to do with the sleep and delay functions which I also don't know how to use. Can anyone help me with this last stage, it sucks that all my coding is complete but I can't get this "twirly" thing to work.
if you want to simultaneously perform the task of
Testing the numbers and
Display the twirly on screen
while the process goes on then you better look into using threads. using POSIX threads you can initiate the task on a thread and the other thread will display the twirly to the user on terminal.
#include<stdlib.h>
#include<pthread.h>
int Test();
void Display();
int main(){
// create threads each for both tasks test and Display
//call threads
//wait for Test thread to finish
//terminate display thread after Test thread completes
//exit code
}
Refer chapter 12 for threads
beginning linux programming ebook
Given the program upon which the user is "waiting", I believe the problem as stated and the solutions using sleep() or threads are misguided.
To produce all the perfect numbers below 10,000 using C on a modern personal computer takes about 1/10 of a second. So any device to show the computer is "happily working away" would either never be seen or would significanly intefere with the time it takes to get the job done.
But let's make a working twirly for perfect number search anyway. I've left off printing the factors to keep this simple. Since 10,000 is too low to see the twirly in action, I've upped the limit to 100,000:
#include <stdio.h>
#include <string.h>
int main()
{
const char *twirly = "|/-\\";
for (unsigned x = 1; x <= 100000; x++)
{
unsigned sum = 0;
for (unsigned i = 1; i <= x / 2; i++)
{
if (x % i == 0)
{
sum += i;
}
}
if (sum == x)
{
printf("%d\n", x);
}
printf("%c\r", twirly[x / 2500 % strlen(twirly)]);
}
return 0;
}
No need for sleep() or threads, just key it into the complexity of the problem itself and have it update at reasonable intervals.
Now here's the catch, although the above works, the user will never see a fifth perfect number pop out with a 100,000 limit and even with a 100,000,000 limit, which should produce one more, they'll likely give up as this is a bad (slow) algorithm for finding them. But they'll have a twirly to watch.
i as integer
loop i: 1 to 10000
loop j: 1 to i/2
sum as integer
set sum = 0
if i%j == 0
sum+=j
return sum==i
if i%100 == 0
str as character pointer
set *str = "|/-\\"
set length = 4
print str[p] using "%c\r" as format specifier
Increment p and assign its modulo by len to p

C programming: I want subtract a weight per second

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.

Resources