Skip to content

Instantly share code, notes, and snippets.

@kotp
Last active August 29, 2015 14:17
Show Gist options
  • Save kotp/210e00496fbb6efe4e93 to your computer and use it in GitHub Desktop.
Save kotp/210e00496fbb6efe4e93 to your computer and use it in GitHub Desktop.
Result of refactoring other code, uses time library and features a proc.
require 'time'
get_time = ->(t) { [t.iso8601, t.usec] }
report = 'something to report with a detailed time: %s'
puts report % get_time[Time.now]
@DouglasAllen
Copy link

Interesting pipe there for the lambda.
But didn't you just slow me down there https://www.omniref.com/ruby/2.2.0/symbols/Proc/yield#annotation=4087638&line=711&hn=1

Anyway this 'will' give the micro seconds

require 'time'
get_time = ->(t) { [t.iso8601(6)] }
get_usec = ->(t) { [t.usec] }
report = 'a detailed string format for time: %s'
puts report % get_time[Time.now.utc] 
puts report % get_usec[Time.now.utc]

It took a little time to get though is why they're different of course.
I get Z on the end and that means Zulu time zone in phonetics.

@DouglasAllen
Copy link

http://www.tutorialspoint.com/c_standard_library/c_function_time.htm

//ctime.c
#include <time.h>
#include <sys/time.h>
#include <ruby.h>

VALUE get_time(VALUE self)
{
  time_t now;
  time(&now);
  return rb_str_new2(ctime(&now));
}

VALUE e_sec(VALUE self)
{
  struct timeval tval;
  gettimeofday(&tval, NULL);
  return INT2NUM(tval.tv_sec);
}

void Init_ctime()
{
  rb_define_global_function("get_time", get_time, 0);
  rb_define_global_function("e_sec", e_sec, 0);
}

@DouglasAllen
Copy link

#extconf.rb

require "mkmf"
create_makefile("ctime")

@DouglasAllen
Copy link

#test.rb

require_relative 'ctime'

puts "Time now is #{get_time}"
puts "#{e_sec} seconds since January 1, 1970"
t1 = Time.new(1970,01,01,0,0,0, "+00:00")# is there something else in Ruby Time to get this?
puts "Time now is #{t1 + e_sec}"
puts "#{system 'date'}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment