Ok, I know this is not the first question about microtime and number_format but it seem there is no one able to come up with a dummy proof answer. So, as the dummy, here is my question:
How can I output my result from 2 microtime(true) variables in millisecondes. By that I mean 1 being 1 milliseconds and 1000 being 1 secondes.
So if it took less then a millisecondes, i get 1. If it took 1/2 of a second, I get 500.
I currently do this:
number_format((microtime(true)-$timetrace), 4)
And I get this:
1,391,490,671.8339
=)
$timetrace was set before in the code as $timetrace = microtime(true). Thansk for the help and if this was answer before in a one line command, I am truly sorry for asking that again.
This has nothing to do with number_format.
My bet is, you did not put what you intended in your $timetrace variable.
See this example:
<?php
$timetrace = microtime(true);
sleep (1); // wait about 1 second
$elapsed_time = microtime(true) - $timetrace;
echo "$elapsed_time<br>";
echo number_format($elapsed_time, 4) . "<br>";
?>
output:
1.0120580196381
1.0121
Based on kuroi neko suggestion, I did built a little funciton and it work perfectly! Thank you a lot!!
Function ms($overall=0)
{
global $timetrace;
global $starttrace;
if ($overall==1){
$result = microtime(true) - $initialtrace;
}else{
$result = microtime(true) - $timetrace;
}
$result = number_format($result, 4);
$result = $result * 1000;
if ($result < 1)$result = 1;
// Reset timetrace
$timetrace = microtime(true);
return $result." ms<br>";
}
In the code I just have to put:
if (isset($timetrace)) echo "CPU$==# initiation time = ".ms();
That give me the time spent between my last echo. (isset is actually a variable I configure at the beginning to see if I am in 'time debugging mode')
If I pass 1 - echo "CPU$==# initiation time = ".ms(1); - I get the result of the total duration of the script since the top of the page instead of the last echo.
Here is a sample of the output:
CPU$==# INSERT = 12.4 ms
CPU$==# DATE SET FOR GOOGLE QUERY = 530.4 ms
CPU$==# GOOGLE QUERY EXECUTED = 308.8 ms
CPU$==# INSERT 606 ROW = 12290.3 ms
CPU$==# CLOSE LOG WITH SUCCESS = 25.4 ms
Success
And yeah, performance is really terrible. The first 530 ms just to prepare the google query is way too high and 12 seconds to insert 600 rows is insane. Something is badly broken somewhere! =) But at least, now I will be able to benchmark my progression.
Thank you!!!
Related
Currently I use the following javascript function to conver seconds to minutes and seconds.
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
If I pass it 235 it returns 3:55
I've tried to convert it to php, but passing 235 to it I get 55
What have I done wrong ?
function fmtMSS($s){
return($s-($s%=60))/60+(9<$s?':':':0')+$s;
};
echo fmtMSS(235);
Thanks.
You have wrong logic part in your PHP version. Take a look at this:
function fmtMSS($s){
return(($s-($s%60))/60).(9<$s?':':':0').$s%60;
};
echo fmtMSS(235);
Sandbox: http://sandbox.onlinephpfunctions.com/code/163b767d435cf9db9058d03e95b873fb07e3fcbd
There is no reason to do it in a one-liner unless its the easiest and most readable way. Don't sacrifice readable code for shorter code.
The below function is the simplest and easiest way to convert seconds into a minute:seconds format. The reason for not using date("H:i", $s) (which would yield the same result) is that it will not scale well, and return incorrect results if $s ever gets high.
Divide by 60, floor it - that will get you the minutes. Multiply it by 60 and subtract it from $s, and you have your seconds.
function fmtMSS($s){
$minutes = floor($s/60);
$seconds = $s-$minutes*60;
return "$minutes:$seconds";
};
echo fmtMSS(235); // 3:55
Live demo
The reason your original code doesn't work, is because you're using + to join strings (as you would in JavaScript). However, in PHP, one uses . to contact two strings. The logic also seems to be a bit incorrect.
<?php
function fmtMSS($s){
$min = floor($s/60);
$sec = $s%60;
return $min.':'.$sec;
};
echo fmtMSS(235);
?>
Use this code- i have just edited your function.
for short:- echo gmdate("i:s", 235);
Here is my pseudo code
For loop repeat 30 times
Call and execute API script which takes less than 1 second
I want the system to sleep for some moment(less than 1 second)
Loop end
I want the above script should finish execution in minimum of 30 seconds (2-3 seconds longer is not a problem but must not less).
Can you write a sample code for me(only time related)
Here's a little program that implements the essence of what I believe you are looking for:
$minTime = 30;
$perSec = 10000;
$start = microtime(TRUE)*$perSec;
print("This must take $minTime seconds.\n");
// Replace this loop with what you actually need done
for ($i=0; $i<10; $i++) { print("Doing stuff #{$i}... "); sleep(1); }
// Check difference in timestamps to calculate remaining time
$remain=($minTime*$perSec-(microtime(TRUE)*$perSec-$start))/$perSec;
var_dump(['remain' => $remain]);
if ($remain > 0) {
print("\n$remain seconds remaining... ");
sleep($remain);
}
print("DONE\n");
This code has been updated to use microtime() instead of time(), which only permitted intervals of integer seconds. On systems that support gettimeofday() we can work with microseconds, instead.
I have PHP array which I use to draw a graph
Json format:
{"y":24.1,"x":"2017-12-04 11:21:25"},
{"y":24.1,"x":"2017-12-04 11:32:25"},
{"y":24.3,"x":"2017-12-04 11:33:30"},
{"y":24.1,"x":"2017-12-04 11:34:25"},
{"y":24.2,"x":"2017-12-04 11:35:35"},.........
{"y":26.2,"x":"2017-12-04 11:36:35"}, ->goes up for about a minute
{"y":26.3,"x":"2017-12-04 11:37:35"},.........
{"y":24.1,"x":"2017-12-04 11:38:25"},
{"y":24.3,"x":"2017-12-04 11:39:30"}
y=is temperature and x value is date time,
as you can see temperature doesn't change so often even if, it change only for max 0.4. But sometimes after a long period of similar values it change for more than 0.4.
I would like to join those similar values, so graph would not have 200k of similar values but only those that are "important".
I would need an advice, how to make or which algorithm would be perfect to create optimized array like i would like.
perfect output:
{"y":24.1,"x":"2017-12-04 11:21:25"},.........
{"y":24.1,"x":"2017-12-04 11:34:25"},
{"y":24.2,"x":"2017-12-04 11:35:35"},.........
{"y":26.2,"x":"2017-12-04 11:36:35"}, ->goes up for about a minute
{"y":26.3,"x":"2017-12-04 11:37:35"},.........
{"y":24.1,"x":"2017-12-04 11:38:25"}
Any help?
As you specified php I'm going to assume you can handle this on the output side.
Basically, you want logic like "if the absolute value of the temperature exceeds the last temperature by so much, or the time is greater than the last time by x minutes, then let's output a point on the graph". If that's the case you can get the result by the following:
$temps = array(); //your data in the question
$temp = 0;
$time = 0;
$time_max = 120; //two minutes
$temp_important = .4; //max you'll tolerate
$output = [];
foreach($temps as $point){
if(strtotime($point['x']) - $time > $time_max || abs($point['y'] - $temp) >= $temp_important){
// add it to output
$output[] = $point;
}
//update our data points
if(strtotime($point['x']) - $time > $time_max){
$time = strtotime($point['x']);
}
if(abs($point['y'] - $temp) >= $temp_important){
$temp = $point['y'];
}
}
// and out we go..
echo json_encode($output);
Hmm, that's not exactly what you're asking for, as if the temp spiked in a short time and then went down immediately, you'd need to change your logic - but think of it in terms of requirements.
If you're RECEIVING data on the output side I'd write something in javascript to store these points in/out and use the same logic. You might need to buffer 2-3 points to make your decision. Your logic here is performing an important task so you'd want to encapsulate it and make sure you could specify the parameters easily.
For a school assignment we need to write a PHP script that counts for 1 second.
The following code I wrote should do exactly that was my thought:
$startTijd = time();
$teller = 0;
while($startTijd == time()){
echo 'Iteratie: ' . $teller . '<br>';
$teller++;
}
However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.
Your code as it is would not work (would not count one second exactly), because time() has a granularity of one second, and you have no guarantees that you landed on your page exactly at the tick of a second. So you need to synchronize.
To be clear, imagine calling time() several times, and let's suppose time() outputs in HH:MM:SS instead of Unix timestamps for legibility's sake:
Code
print time()
print time()
print time()
...
Output:
01:15:17
01:15:17
01:15:17
...
01:15:18
01:15:18
01:15:18
...
Your program probably currently does not work correctly because even in the little time that the loop runs, it generates a fantastic quantity of output (as can be seen above, time() remains "valid" for up to a whole second, and in that time a loop can execute lots of times). If there's some sort of resource limit on the PHP process, it's possible that this drives the process over its quota, resulting in the 502 error. You can check that by removing the echo from the loop, and just adding echo "Done." at the end.
You want to count between the instant in time in which time() transitions from 01:15:17 to 01:15:18, up to the instant when it again transitions to 01:15:19. Those instants will be separated by exactly one second.
What you would need to do is:
$startTijd = time()+1; // It is now maybe 01:15:17.93. We want to start
// counting at 01:15:18, so we need to wait for it.
while($startTijd !== time()) {
// Do nothing except maybe a very brief sleep to save CPU
usleep(5); // this is optional anyway.
}
// It is now 01:15:18.000003 and $startTijd is 01:15:18
$teller = 0;
// time() will remain equal to 01:15:18 for one second,
// while wall clock time increases from 01:15:18.000003 to 01:15:18.999999
while ($startTijd == time()) {
// Don't output anything here
$teller++;
}
// New transition detected.
// It is now e.g. 01:15:19.000137 and time() says 01:15:19.
echo 'Iteratie: ' . $teller . '<br>';
Alternately you can use microtime(true):
$teller = 0;
$endTijd = microtime(true) + 1.0;
while ($endTijd >= microtime(true)) {
// Don't output anything here
$teller++;
}
echo 'Iteratie: ' . $teller . '<br>';
Your code makes no sense... your while statment is only true if you computer is fast enough.
$startTijd = 100; # you set here the time represented by a number
while(100 == time() #101) { # here time is some milliseconds or seconds in the future
so after a second your while stops so that make not so much sense. Then use
while(true) {
and stop the while with a condition insight the while loop.
I have a small code as part of a huge file as follows:
if(($lastLogTime + $logOffset)>= $text1)
{
echo $text1.'<br>';
$uptime=$uptime + (($text1 - $lastLogTime)/60000);
echo ($text1 - $lastLogTime).'<br>';
fwrite($fd, $uptime.',');
echo $uptime.'<br><br>';
$lastLogTime = ($lastLogTime + 1800000);
echo $lastLogTime.' ME <br>';
}
The weird part is the output for the final $lastLogTime is NOT getting added by the 1800000 OR a variable called $logInterval = 1800000 which was initialized earlier.
The output is
1298083876650 - i.e lastLogtime
1298083877661 - text1
1011 - the difference
0.01685 - uptime
1298085676650 ME - damn ! doesn't get added by 1800000
NEW EDIT :
I solved it ! bad answers guys.. Thanks for the time anyways.
Am i the only one facing weird shhit like this ?
I suspect it has something to do with this:
What's the maximum size for an int in PHP?
Check out the php date function. Though working with dates can be tedious, converting everything to seconds normally isn't the best approach.
http://php.net/manual/en/function.date.php